jQuery学习笔记1

jQuery学习笔记1

开始之前:http://docs.jquery.com/ 是jQuery文档的网站, https://jsfiddle.net/是js的在线验证工具。

1.首先复习一下html, css, js三个文件的协同作用
  • html负责内容elements和骨架tags,div
  • css负责格式样式大小、颜色等
  • js负责动作效果,操作html

JQuery是一个面向javascript的工具库,基于DOM-Document Object Model文档对象模型,通过使用jQuery可以方便实现效果。

1.1-html包含css与JavaScript的基本骨架代码
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title></title>
5. <link rel="stylesheet" type="text/css" href="stylesheet.css"/>
6. <script type="text/javascript" src="script.js"></script>
7. </head>
8. <body>
9. <div id="red" ></div>
10. </body>
11. </html>
2.好,让我们开始接触jQuery

Getting Started

Next, we’ll need to start up our jQuery magic using the $(document).ready(); syntax you’ve seen. It works like this:

1. $() says, "hey, jQuery things are about to happen!"是把()内的东东转化成jQuery的object,从而有后面的.ready这个method
2. Putting document between the parentheses tells us that we're about to work our magic on the HTML document itself.
3. .ready(); is a function, or basic action, in jQuery. It says "hey, I'm going to do stuff as soon as the HTML document is ready!"
4. Whatever goes in .ready()'s parentheses is the jQuery event that occurs as soon as the HTML document is ready.

So,

$(document).ready(something);

//就是对于document来说,当你ready的时候,就执行something

3.好,我们来玩玩嵌套的method
1. $(document).ready(
2. function(){
3. $('div').mouseenter(
4. function(){
5. $('div').fadeTo('fast',1);
6. }
7. );
8. $('div').mouseleave(
9. function(){
10. $('div').fadeTo('fast',0.5)
11. }
12. );
13. }
14. );

这个就是先(document)ready , 然后(div)mouseenter,最后(div)fadeTo.

实际上这个排版不是很通用,通用的排版应该是:

1. $(document).ready(function(){
2. $('div').mouseenter(function(){
3. $('div').fadeTo('fast',1);
4. });
5. $('div').mouseleave(function(){
6. $('div').fadeTo('fast',0.5)
7. });
8. });
4.关于CSS中的selector

在有列表情况下,如果想通过js对列表中的某一项进行操作,需要用到selector来指定是修改哪一个:比如:

1. <ol>
2. <li>Start with the function keyword</li>
3. <li>Inputs go between ()</li>
4. <li>Actions go between {}</li>
5. <li id="no4" class="hide">jQuery is for chumps!</li>
6. </ol>

这个html列表,我们jQuery可以用CSS的这4种方法来指明:

  • id
  • class
  • nth-child(n)
  • last-child
1. // Write your jQuery code on line 3!
2. $(document).ready(function() {
3. var $target = $('li#no4')   //use an id or class
4. //var $target = $('li.hide')    //use a class
5. //var $target = $('li:nth-child(4)') //use "nth-child(n)"
6. //var $target = $('li:last-child')  //use "last-child"
7. $target.fadeOut('fast');
8. });

  另外,需要同时定位2个标签、class、id时,还可使用如下方式:

    $('p, li').fadeOut('slow');
    $('.red, .pink').fadeOut('slow');
    $('#green, #blue').fadeOut('slow');
5.使用‘this’,在jQuery中

this 这个key word在jQuery中可以理解为:当你涉及到诸如mouseenter, click这样的事件类function时,使用this可以在你后续处理动作时指定就是你上次事件指向的那个object,比如有多个div,当你点击了第一个div时,你要让它消失,就在click后用this来让它消失:

1. $(document).ready(function() {
2. $('div').click(function() {
3. $(this).fadeOut('slow'); //对上次事件的对象进行fadeOut操作
4. });
5. });

原html部分代码如下:

1. <body>
2. <div></div>
3. <div></div>
4. <div></div>
5. <div></div>
6. </body>
6.关于Toggling Our Panel的实例

本实例要实现点击下拉一个div出来的效果,先用display:none在CSS中将div隐藏,再在js中调用jQuery的slideToggle()函数:

部分html代码如下:

1. <body>
2. <div class="panel">
3. <br />
4. <br />
5. <p>Now you see me!</p>
6. </div>
7. <p class="slide"><div class="pull-me">Slide Up/Down</div></p>
8. </body>

全部CSS代码如下:

1. body {
2. margin:0 auto;
3. padding:0;
4. width:200px;
5. text-align:center;
6. }
7. .pull-me{
8. -webkit-box-shadow: 0 0 8px #FFD700;
9. -moz-box-shadow: 0 0 8px #FFD700;
10. box-shadow: 0 0 8px #FFD700;
11. cursor:pointer;
12. }
13. .panel {
14. background: #ffffbd;
15. background-size:90% 90%;
16. height:140px;
17. display:none;  /*there we go*/
18. font-family:garamond,times-new-roman,serif;
19. }
20. .panel p{
21. text-align:center;
22. }
23. .slide {
24. margin:0;
25. padding:0;
26. border-top:solid 2px #cc0000;
27. }
28. .pull-me {
29. display:block;
30. position:relative;
31. right:-25px;
32. width:150px;
33. height:20px;
34. font-family:arial,sans-serif;
35. font-size:14px;
36. color:#ffffff;
37. background:#cc0000;
38. text-decoration:none;
39. -moz-border-bottom-left-radius:5px;
40. -moz-border-bottom-right-radius:5px;
41. border-bottom-left-radius:5px;
42. border-bottom-right-radius:5px;
43. }
44. .pull-me p {
45. text-align:center;
46. }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)

全部js代码如下:

1. $(document).ready(function(){
2. $('.pull-me').click(
3. function(){
4. $('.panel').slideToggle('slow');
5. });
6. });

到这里就掌握了基本的jQuery用法,完成了对于jQuery函数和selector的学习,接下来要学习jQuery的“modify HTMLElements”

Any time you have questions about what jQuery can do or how it works, you can always check out the jQuery documentation, which covers every aspect of the library. 所以:http://docs.jquery.com/ 是jQuery文档的网站。

7.开始修改HTML中的元素

Dynamically adding elements to our HTML page is a powerful tool—it lets us modify not only the formatting, but the actualstructure of our websites in response to a user’s actions. 不仅可以改格式,还可以改页面结构。
不单是这样:

   $p = $('p');

还可以是这样:

   $p = $("<p>I'm a new paragraph!</p>");	//把一个String放到$p变量里去
7.1  -Inserting Elements
We can insert our newly created elements using a few jQuery actions.

`.append()` inserts the specified element as the last child of the target element. `.prepend()` inserts the specified element as the *first* child of the target element. If we have a div of class `.info`,:
  1. $(".info").append("

    Stuff!

    ");//inserts element as the last child of the target
  2. $(".info").prepend("

    Stuff!

    "); //inserts as the first
	$('<p>Stuff!</p>').appendTo('.info');	//appendTo('.target tag'); = append
  
7.2   - before and after
用.before 和 .after来定位where we insert an element. 语法如下:
    $('target').after('<tag>To add</tag>');
target 就是定位加入<tag>To add</tag>的位置,在target后面加入。

html示例代码:

1. <body>
2. <div class="container">
3. <h2>Greetings</h2>
4. <div id="one">Div #1</div>
5. <div id="two">Div #2</div>
6. </div>
7. </body>

js代码:

1. $(document).ready(function(){
2. $("div#one").after("<p>I'm joined here.</p>");
3. });
7.3 - move around

        js代码:

	$(document).ready(function(){
    	    $("div#one").after("<p>I'm joined here.</p>"); //insert the <p> tag
    	    var $paragraph = $("p");	//move the <p> tag in html
    	    $("div#two").after($paragraph);
	});
7.4 - removing elements
	we have two jQuery functions, `.empty()` and `.remove()`, that help us delete content from our pages.

`.empty()` deletes an element's content and *all its descendants*(子节点). For instance, if you `.empty()` an `'ol'`, you'll also remove all its `'li'`s and their text.

`.remove()`, not only deletes an element's content, but deletes the element itself.

	js代码:
1. $(document).ready(function(){
2. $("div#one").after("<p>I'm joined here.</p>");//create a <p> tag after div#one
3. var $paragraph = $("p");    //value the <p>tag into a var for moving
4. $("div#two").after($paragraph); //move the <p> tag after div#two
5. $('p').remove();    //remove the <p>tag
6. });
7.5. Adding and Removing Classes

我们没必要去一个个element的删除修改,可以好好用jQuery的功能来切换class, CSS, and HTML elements.

.addClass().removeClass() 两个函数来完成这个功能。

for example, you have a `highlighted` class that you want to apply to an element when clicked.

The syntax looks like this:
  1. $(‘selector’).addClass(‘className’);
  2. $(‘selector’).removeClass(‘className’);
  

CSS部分代码:

1. .highlighted {
2. -webkit-box-shadow: 0 0 8px #FFD700;
3. -moz-box-shadow: 0 0 8px #FFD700;
4. box-shadow: 0 0 8px #FFD700;
5. cursor:pointer;
6. }

JS部分代码:

1. $(document).ready(function(){
2. $("div#text").click(function(){
3. $(this).addClass('highlighted'); //We've supplied the HTML and CSS
4. });
5. });
7.6 - Toggling Class(推拉Class:点击添加-再点击去掉the class)

    如果一个html元素,有了class就给它去掉;没有就给它加上。使用函数:.toggleClass():

    $(this).toggleClass('highlighted');  //change the above addClass into toggleClass
  
7.7 - 修改CSS参数,Chaning your Style

    要修改CSS中的参数,比如颜色,对jQuery来说,也是个snap.

  • Resize the elements: .width();  .height();  e.g:  $(“div”).height(“100px”);
  • 对CSS操作:.css e.g.:  $(“div”).css(“background-color”,"#008800");
  • js示例代码如下
1. $(document).ready(function(){
2. $("div").height(200);
3. $("div").width(200);
4. $("div").css("border-radius","10px");
5. });
7.8 - 修改html内容:modifing content

    使用 .html() and .val(); 可以修改html内容,比如:

        1. get the HTML contents of the first div it finds:

           $('div').html("I love jQuery!");

        2. **.val()** 从表单(form)元素中获取值. For example:

1. 
2. $('input:checkbox:checked'.val();

       would get the value of the first checked checkbox that jQuery finds.

1. $(document).ready(function(){
2. $('p').html("jQuery magic in action!");
3. });
7.9 - 一个html表单及内容添加实例

        这里我们要用前面所学的jQuery修改html内容的所有函数来完成一个表单的输入,并显示结果在html页面上。
        $(selector for a form).val()   – 这里要主要表单的定位方法:‘input[name = formName]’
        $(".target").append(’’ + variable + ‘</html tag string>’);

1. $(document).ready(function(){
2. $('#button').click(function(){
3. var toAdd = $('input[name=checkListItem]').val();
4. $(".list").append('<div class="item">' + toAdd + '</div>');
5. });
6. });

对应的html代码:

1. <body>
2. <h2>To Do</h2>
3. <form name="checkListForm">
4. <input type="text" name="checkListItem"/>
5. </form>
6. <div id="button">Add!</div>
7. <br/>
8. <div class="list"></div>
9. </body>
8. $(document).on(); 与 $(document).ready();的区别

    在上面的例子中,如果我们想通过单击来去掉通过表单添加的items,我们可能会想到如下的方法:

1. 
2. $('.item').click(function() {
3. $(this).remove();
4. });

   但是你会发现这个是不work的,因为$(document).ready();执行时,并没有class=item的元素。class=item的元素是click button后,我们添加进html的。

   此时就需要用到 $(document).on();函数:

1. 
2. $(document).on('event', 'selector', function() {
3. Do something!
4. });

   这里我们的 ’event’ = ‘click’, ‘selector’=’.item’    js代码:

1. $(document).ready(function(){
2. $('#button').click(function(){
3. var toAdd = $('input[name=checkListItem]').val();
4. $(".list").append('<div class="item">' + toAdd + '</div>');
5. });
6. 
7. $(document).on('click','.item',function(){
8. $(this).remove();
9. });
10. });

You Did It!

Great work! You now know how to dynamically update the content of your HTML page, including adding and removing elements.

Now that you can handle manipulating the DOM on the fly, the hard part is over. In the next two lessons, we’ll cover a wider range of jQuery event handlers and effects, which will allow you to apply your core programming skills to a variety of challenges.

9.复习jQuery的Events

我们已经学了很多关于jQuery events,来复习一下基础的东西。

一般是以下的套路(模板):

1. $(document).ready(function() {
2. $('thingToTouch').event(function() {
3. $('thingToAffect').effect();
4. });
5. });

“thing to touch” is the HTML element you’ll

click on, hover over, or otherwise interact with,

and “thing to affect” is the HTML element that:

fades away, changes size,

or undergoes some other transformation.

我们已经学了很多关于jQuery events,来复习一下基础的东西。

一般是以下的套路:

有时候这些元素是一个或者同样的,你要hover over a

来改变它的不透明度opacity。

有时你要和不同的元素互动,例如你要点击一个button来resize it.

有时候如果你想要一个效果,不要.click 或.hover这样的事件来触发,你可以跳过上面的第二行。

10.总结一下events & actions

    10.1 Events:

  • .click
  • .hover
  • .dblclick //double click
  • .mouseenter
  • .mouseleave

    10.2 Actions:

  • .fadeOut(‘fast’)  //fast, slow, …
  • .hide();  //hide
  • .slideToggle(‘slow’);
  • …..Change styles……
  • .addClass()
  • .removeClass

下面这个例子是我们常用的鼠标移上来应用一个class,然后移除时候remove that class. 

这里在 $(‘div’).hover(A,B);下并排了两个function(){ addClass }, [comma] — function(){ removeClass }, 【中间的逗号很重要!】

1. $(document).ready(function(){
2. $('div' ).hover(
3. function(){
4. $(this).addClass('active');
5. },  //separated by a comma. The comma is very important!
6. function(){
7. $(this).removeClass('active');
8. }
9. );
10. });

实际上.hover(Aaction,Baction);就是这么来的。

11. 响应事件:.focus()

.focus() event 是hover和click都响应的事件,有些html元素可以receive focus。
常见的有