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的基本骨架代码



    
        
        
        
    
    
        


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:

$() says, "hey, jQuery things are about to happen!"是把()内的东东转化成jQuery的object,从而有后面的.ready这个method
Putting document between the parentheses tells us that we're about to work our magic on the HTML document itself.
.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!"
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

$(document).ready(
    function(){
        $('div').mouseenter(
            function(){
            $('div').fadeTo('fast',1);    
            }
        );
        $('div').mouseleave(
            function(){
            $('div').fadeTo('fast',0.5)
            }  
        );
    }
);


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

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

$(document).ready(function(){
    $('div').mouseenter(function(){
        $('div').fadeTo('fast',1);    
    });
    $('div').mouseleave(function(){
        $('div').fadeTo('fast',0.5)
    });
});


4.关于CSS中的selector

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

<ol>
   <li>Start with the function keywordli>
   <li>Inputs go between ()li>
   <li>Actions go between {}li>
   <li id="no4" class="hide">jQuery is for chumps!li>
ol>

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

  • id
  • class
  • nth-child(n)
  • last-child

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

  另外,需要同时定位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来让它消失:
$(document).ready(function() {
    $('div').click(function() {
        $(this).fadeOut('slow'); //对上次事件的对象进行fadeOut操作
    });
});
原html部分代码如下:

        

6.关于Toggling Our Panel的实例

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


Now you see me!

Slide Up/Down



全部CSS代码如下:
body {
    margin:0 auto;
    padding:0;
    width:200px;
    text-align:center;
}
.pull-me{
    -webkit-box-shadow: 0 0 8px #FFD700;
    -moz-box-shadow: 0 0 8px #FFD700;
    box-shadow: 0 0 8px #FFD700;
    cursor:pointer;
}
.panel {
    background: #ffffbd;
    background-size:90% 90%;
    height:140px;
    display:none;  /*there we go*/
    font-family:garamond,times-new-roman,serif;
}
.panel p{
    text-align:center;
}
.slide {
    margin:0;
    padding:0;
    border-top:solid 2px #cc0000;
}
.pull-me {
    display:block;
    position:relative;
    right:-25px;
    width:150px;
    height:20px;
    font-family:arial,sans-serif;
    font-size:14px;
    color:#ffffff;
    background:#cc0000;
    text-decoration:none;
    -moz-border-bottom-left-radius:5px;
    -moz-border-bottom-right-radius:5px;
    border-bottom-left-radius:5px;
    border-bottom-right-radius:5px;
}
.pull-me p {
    text-align:center;
}


全部js代码如下:
$(document).ready(function(){
    $('.pull-me').click(
        function(){
        $('.panel').slideToggle('slow');
    });
});
到这里就掌握了基本的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 = $("

I'm a new paragraph!

"
); //把一个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,:

	$(".info").append("

Stuff!

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

Stuff!

"
); //inserts as the first
	$('

Stuff!

'
).appendTo('.info'); //appendTo('.target tag'); = append

    7.2   - before and after
 
  
	用.before 和 .after来定位where we insert an element. 语法如下:
	    $('target').after('To add');
	target 就是定位加入To add的位置,在target后面加入。

html示例代码:

    
        

Greetings

Div #1
Div #2

js代码:

$(document).ready(function(){
    $("div#one").after("

I'm joined here.

"); });

    7.3 - move around
        js代码:
	$(document).ready(function(){
    	    $("div#one").after("

I'm joined here.

"); //insert the

tag     var $paragraph = $("p"); //move the

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代码:

$(document).ready(function(){
    $("div#one").after("

I'm joined here.

");//create a

tag after div#one var $paragraph = $("p"); //value the

tag into a var for moving $("div#two").after($paragraph); //move the

tag after div#two $('p').remove(); //remove the

tag });


    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:

$('selector').addClass('className');
$('selector').removeClass('className');

CSS部分代码:

.highlighted {
    -webkit-box-shadow: 0 0 8px #FFD700;
    -moz-box-shadow: 0 0 8px #FFD700;
    box-shadow: 0 0 8px #FFD700;
    cursor:pointer;
}

JS部分代码:

$(document).ready(function(){
    $("div#text").click(function(){
        $(this).addClass('highlighted'); //We've supplied the HTML and CSS
    });
});

    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示例代码如下
$(document).ready(function(){
    $("div").height(200);
    $("div").width(200);
    $("div").css("border-radius","10px");
});

    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:


      $('input:checkbox:checked'.val();
       would get the value of the first checked checkbox that jQuery finds.
$(document).ready(function(){
    $('p').html("jQuery magic in action!");
});
    7.9 - 一个html表单及内容添加实例

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

$(document).ready(function(){
    $('#button').click(function(){
        var toAdd = $('input[name=checkListItem]').val();
        $(".list").append('
' + toAdd + '
'); }); });

对应的html代码:

	
		

To Do

Add!



8. $(document).on(); 与 $(document).ready();的区别

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


  $('.item').click(function() {
     $(this).remove();
  });
   但是你会发现这个是不work的,因为$(document).ready();执行时,并没有class=item的元素。class=item的元素是click button后,我们添加进html的。
   此时就需要用到 $(document).on();函数:

  $(document).on('event', 'selector', function() {
     Do something!
  });
   这里我们的 'event' = 'click', 'selector'='.item'

   js代码:

$(document).ready(function(){
    $('#button').click(function(){
        var toAdd = $('input[name=checkListItem]').val();
        $(".list").append('
' + toAdd + '
'); }); $(document).on('click','.item',function(){ $(this).remove(); }); });

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,来复习一下基础的东西。
一般是以下的套路(模板):
  $(document).ready(function() {
    $('thingToTouch').event(function() {
        $('thingToAffect').effect();
    });
  });
"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 }, 【中间的逗号很重要!】
$(document).ready(function(){
  $('div' ).hover(
    function(){
        $(this).addClass('active');
    },  //separated by a comma. The comma is very important!
    function(){
        $(this).removeClass('active');
    }
  );
});
实际上.hover(Aaction,Baction);就是这么来的。

11. 响应事件:.focus()

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