jQuery 笔记

来源:互联网 发布:网络市场监管 编辑:程序博客网 时间:2024/06/16 09:57
1.$('div').html()是使用标签选择器获取div标签,在div中显示括号中的内容 .
对应于javascript中的各类选择器,如:
$('*') ——所有元素
$('#lastname') ——id="lastname" 的元素
$('.intr') ——所有 class="intro" 的元素

$('p') ——所有 <p> 元素

$('.intro .demo')——所有class =“intro” 而且也等于“demo”的元素


2.jQuery对象与DOM对象不同

<p id ="aha"></p>... //用js的办法 var p = getElementById("aha">p.innerHtml = '你需要我的帮助吗?';p.style.color = 'red';//jQuery的办法var $p =$('#aha');$p.html('你需要我的帮助吗?').css('color','red');

通过标准的JavaScript操作DOM与jQuyer操作DOM的对比,我们不难发现:

  1. 通过jQuery方法包装后的对象,是一个类数组对象。它与DOM对象完全不同,唯一相似的是它们都能操作DOM。
  2. 通过jQuery处理DOM的操作,可以让开发者更专注业务逻辑的开发,而不需要我们具体知道哪个DOM节点有那些方法,也不需要关心不同浏览器的兼容性问题,我们通过jQuery提供的API进行开发,代码也会更加精短。
3.jQuery对象转为DOM对象

<div>1</div><div>2</div><div>3</div>...//将第一个div内容改为红色法一var $div = $('div');var div = $div[0]; //转为DOM对象div.style.color = 'red';法二  直接利用get()函数,其实为上述方法的封装var $div =$('div');var div = $div.get(0);div.style.color ='red';

4.DOM转为jQuery

<div>1</div> <div>2</div><div>3</div>...//将第一个div内容改为红色var div = dovument.getElementByTagName('div');var $div = $(div); var $first = $div.first();$first.css('color','red');


5.层级选择器

例如 $('div  > p') 所有div下的第一层里的所有p

$('div p')  div下任意层级的p

$('.prev + next') class=“prev”的元素的下一个元素next


<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body><h2>子选择器与后代选择器</h2><div class="left">    <div class="aaron">        <p>div下的第一个p元素</p>    </div>    <div class="aaron">        <p>div下的第一个p元素</p>    </div></div><div class="right">    <div class="imooc">        <article>            <p>div下的article下的p元素</p>        </article>    </div>    <div class="imooc">        <article>            <p>div下的article下的p元素</p>        </article>    </div></div><h2>相邻兄弟选择器与一般兄弟选择器</h2><div class="bottom">    <div>兄弟节点div, +~选择器不能向前选择</div>    <span class="prev">选择器span元素</span>    <div>span后第一个兄弟节点div</div>    <div>兄弟节点div        <div class="small">子元素div</div>    </div>    <span>兄弟节点span,不可选</span>    <div>兄弟节点div</div></div><script type="text/javascript">//$('div >p').css('border','1px solid red');    $('div p').css('border','1px solid blue');    $('.prev + div').css('border','1px solid red');    $('.prev ~ div').css('border','1px solid red');</script></body></html>


例如:

 <h2>相邻兄弟选择器与一般兄弟选择器</h2>    <div class="bottom">        <div>兄弟节点div, +~选择器不能向前选择</div>        <span class="prev">选择器span元素</span>        <div>span后第一个兄弟节点div</div>        <div>兄弟节点div            <div class="small">子元素div</div>        </div>        <span>兄弟节点span,不可选</span>        <div>兄弟节点div</div>    </div>    <script type="text/javascript">        //相邻兄弟选择器        //选取prev后面的第一个的div兄弟节点    $('.prev+div').css("border", "3px groove blue");    </script>
结果是是span后第一个兄弟节div  这句话变成蓝框。

$('.prev ~ div')  .prev之后 (不能向前选择)所有的同父元素的兄弟元素中的div 例如上面的

span后第一个兄弟节点div   兄弟节点div     兄弟节点div 三个会变成蓝框


6.筛选选择器  //这里的div都是 class=div

$('.div :first') 第一个div

$('.div:last)最后一个div

$('div:even') 偶数个div 第一个div记为0

$('div:odd')奇数个div

<div class="left">        <div class="aaron">            <p>:lt(3)</p>        </div>        <div class="aaron">            <p>:lt(3)</p>        </div>        <div class="aaron">            <p>:eq(2)</p>        </div>        <div class="aaron">        </div>        <div class="aaron">            <p>:gt(3)</p>        </div>        <div class="aaron">            <p>:gt(3)</p>        </div>    </div>

$('.aaron:eq(2)') 编号为2的aaron被选中 从0开始

$('.aaron:gt(3)')大于3的aaron被选中

$(".aaron:lt(2)")小于2
<div class="left">        <div>            <input type="checkbox" name="a" />            <p>Aaron</p>        </div>        <div>            <input type="checkbox" name="b" />            <p>慕课</p>        </div>        <div>            <input type="checkbox" name="c" checked="checked" />            <p>其他</p>        </div>    </div>    <script type="text/javascript">        //:not 选择所有元素去除不匹配给定的选择器的元素        //选中所有紧接着没有checked属性的input元素后的p元素,赋予颜色        $('input:not(:checked) + p').css("background-color", "#CD00CD");    </script>

$('input:not (:checked) + p') 
选中所有紧接着没有checked属性的input元素后的p元素,赋予颜色
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body><h2>基本筛选器</h2><h3>:first/:last/:even/:odd</h3><div class="left">    <div class="div">        <p>div:first</p>        <p>:even</p>    </div>    <div class="div">        <p>:odd</p>    </div>    <div class="div">        <p>:even</p>    </div>    <div class="div">        <p>:odd</p>    </div>    <div class="div">        <p>:even</p>    </div>    <div class="div">        <p>div:last</p>        <p>:odd</p>    </div></div><script type="text/javascript">    //$('.left:first').css('border','1px solid red');  //left    //$('.div:first').css('border','1px solid red');//第一个div的内容有红框    //$('.div:last').css('border','1px solid red');//最后一个div内容有红框    //$('.div:even').css('border','1px solid red');//偶数个div被选中 从0开始计数    //$('.div:odd').css('border','1px solid blue');//奇数个   // $('.div:eq(2)').css('border','1px solid blue')//0开始  第二个div    //$('.div:gt(2)').css('border','1px solid blue')//0开始 比2大的div 不包括2    //$('.div:lt(3)').css('border','1px solid blue')//0开始比3小 不包括3</script><h3>:not</h3><div class="left">    <div>        <input type="checkbox" name="a" />        <p>Aaron</p>    </div>    <div>        <input type="checkbox" name="b" />        <p>慕课</p>    </div>    <div>        <input type="checkbox" name="c" checked="checked" />        <p>其他</p>    </div></div><script>    $('input:not(:checked)+p').css('background-color','blue')//没有checked属性的</script></body></html>

7.内容筛选选择器

 <div class="left">        <div class="div">            <p>:contains</p>        </div>        <div class="div">            <p>:contains</p>        </div>        <div class="div">            <p>                <span>:has</span>            </p>        </div>        <div class="div">            <p>:contains</p>        </div>    </div>    <script type="text/javascript">        //查找所有class='div'中DOM元素中包含"contains"的元素节点        //并且设置颜色        $(".div:contains('contains')").css("color", "#CD00CD");    </script>   <script type="text/javascript">        //查找所有class='div'中DOM元素中包含"span"的元素节点        //并且设置颜色        $(".div:has('span')").css("color", "blue");    </script>
$(".div:contains('contains')")  class=div下的内容包括contains的文本的元素被选中

$(".div:has('spam')") class = div下包括span标签的元素被选中

:contains与:has都有查找的意思,但是contains查找包含“指定文本”的元素,has查找包含“指定元素”的元素

如果:contains匹配的文本包含在元素的子元素中,同样认为是符合条件的。

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body><h2>内容筛选器</h2><h3>:contains/:has</h3><div class="left">    <div class="div">        <p>2contains</p>    </div>    <div class="div">        <p>:containsdd</p>    </div>    <div class="div">        <p>            <span>:has</span>        </p>    </div>    <div class="div">        <p>:contains</p>    </div></div><script>    //$(".div:contains('contains')").css('color','red');//包含contains字样的.div被选中   // $(".div:has('span')").css('color','blue');//.div下有span标签的被选中</script><h3>:parent/:empty</h3><div class="left">    <div class="aaron">        <a>hah..</a>    </div>    <div class="aaron">sss        <a>:t</a>    </div>    <div class="aaron">        <a>:parent</a>    </div>    <div class="aaron">        <a></a>    </div></div><script type="text/javascript">   // $('a:parent').parent().css('border','1px solid red');//不为空的a标签  的父级元素被选中    $('a:empty').text('hah').css('border','1px solid red');</script></body></html>
$("a:parent").parent().css("border", "3px groove blue");:parent意为,有子元素或者文本的元素,就是不为空的元素!=""a:parent是不为空的a元素

.parent(),就是他的父级元素

$('a:empty') 不包含子元素或文本的a元素被选中

a:parent选择的是 包含子元素或文本的a元素

8.可见性筛选选择器

$(':visible') 选择所有显示的元素

$(':hidden')选择所有隐藏的元素

元素可以被认为是隐藏的几个情况:

  • 他们的CSS display值是none
  • 他们是type="hidden"的表单元素。
  • 它们的宽度和高度都显式设置为0。
  • 一个祖先元素是隐藏的,因此该元素是不会在页面上显示。

元素visibility: hiddenopacity: 0被认为是可见的,因为他们仍然占据布局空间。在动画,隐藏一个元素,该元素被认为是可见的直到动画结束。

<!DOCTYPE html><html><head>  <style>  div { width:70px; height:40px; background:#ee77ff; margin:5px; float:left; }  span { display:block; clear:left; color:red; }  .starthidden { display:none; }  </style>  <script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script></head><body>  <span></span>  <div></div>  <div style="display:none;">Hider!</div>  <div></div>   <div class="starthidden">Hider!</div>  <div></div>  <form>    <input type="hidden" />     <input type="hidden" />    <input type="hidden" />  </form>  <span>   </span><script>// in some browsers :hidden includes head, title, script, etc...var hiddenEls = $("body").find(":hidden").not("script"); $("span:first").text("Found " + hiddenEls.length + " hidden elements total.");$("div:hidden").show(3000);$("span:last").text("Found " + $("input:hidden").length + " hidden inputs.");</script> </body></html>

结果

 

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <div class="left">        <div class="div">            <a>dispaly</a>            <p id="div1" style="display: none">display</p>        </div>        <div class="div">            <a>width</a>            <a>height</a>            <p id="div2" style="width: 0;height: 0;">width height</p>        </div>        <div class="div">            <a>visibility</a>            <p id="div3" style="visibility: hidden;opacity: 0">visibility</p>        </div>    </div>    <div id="show"></div><script>    function show(elem) {        if(elem instanceof jQuery){            $('#show').html('元素的长度 = '+ elem.length)        }else {            alert(elem+'不是jquery对象');        }    }    //show($('#div1:visible'));//0    //show($('#div1:hidden'));//1    //show($('#div2:visible'));//0    //show($('#div2:hidden'));//1    //show($('#div3:visible'));//1    //show($('#div3:hidden'));//0</script></body></html>结论:只有visibility为hidden和opacity为0时jquery可以识别出来 

9.属性筛选选择器

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body><div class="left" testattr="true" >    <div class="div" testattr="true" name='p1 '>        <a>[att=val]</a>    </div>    <div class="div" testattr="true" p2>        <a>[att]</a>    </div>    <div class="div" testattr="true" name="-">        <a>[att|=val]</a>    </div>    <div class="div" testattr="true" name="a b">        <a>[att~=val]</a>    </div></div><script>//$('div[name=p1]').css('color',' red');//name属性为p1的所有div    //$('div[name]').css('color',' red')//有name属性的div被选中    //$("div[name |='p1']").css('color',' red')//name属性只为p1的div    //$("div[name ~='a']").css('color',' red')//name属性有a或者a 空格形式的div</script><div class="left" testattr="true" >    <div class="div" testattr="true"  name='imooc-aaorn'>        <a>[att^=val]</a>    </div>    <div class="div" testattr="true"  name='aaorn-imooc'>        <a>[att$=val]</a>    </div>    <div class="div" testattr="true"  name="attrtest-selector">        <a>[att*=val]</a>    </div>    <div class="div" name="a b">        <a>[att!=val]</a>    </div></div><script>    //$('div[name^=imooc]').css('color','blue');//以imooc开头的name属性的div被选中    //$('div[name$=imooc]').css('color','blue');//以imooc结尾的name属性的div被选中    //$('div[name*=test]').css('color','blue');//包含test字符串的name属性的div被选中    $('div[testattr!=true]').css('color','blue');//testattr中不包含true的div</script></body></html>

10.子元素筛选选择器

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body><div class="left first-div">    <div class="div">        <a>:first-child</a>        <a>第二个元素</a>        <a>:last-child</a>    </div>    <div class="div">        <a>:first-child</a>    </div>    <div class="div">        <a>:first-child</a>        <a>第二个元素</a>        <a>:last-child</a>    </div></div><script>    //$('.div a:first-child').css('color','red'); //class为div下的第一个a标签    //$('.div a:last-child').css('color','red');//.div下的最后一个a标签    //$('.div a:only-child').css('color','red')//只有唯一一个a标签的.div被选中</script><div class="left last-div"><div class="div">    <a>:first-child</a>    <a>第二个元素</a>    <a>第三个元素</a>    <a>:last-child</a></div><div class="div">    <a>:first-child</a>    <a>第二个元素</a></div><div class="div">    <a>:first-child</a>    <a>第二个元素</a>    <a>第三个元素</a>    <a>:last-child</a></div></div><script>    //$('.last-div a:nth-child(2)').css('color','blue');//第二个a标签被选中  从1开始    $('.last-div a:nth-last-child(2)').css('color','blue')//倒数第二个a标签被选中  从1开始</script></body></html>总结:eq方法用于多个同级元素的筛选   nth-child用于多个子元素的筛选

  1. :first只匹配一个单独的元素,但是:first-child选择器可以匹配多个:即为每个父级元素匹配第一个子元素。这相当于:nth-child(1)
  2. :last 只匹配一个单独的元素, :last-child 选择器可以匹配多个元素:即,为每个父级元素匹配最后一个子元素
  3. 如果子元素只有一个的话,:first-child与:last-child是同一个
  4.  :only-child匹配某个元素是父元素中唯一的子元素,就是说当前子元素是父元素中唯一的元素,则匹配
  5. jQuery实现:nth-child(n)是严格来自CSS规范,所以n值是“索引”,也就是说,从1开始计数,:nth-child(index)从1开始的,而eq(index)是从0开始的
  6. nth-child(n) 与 :nth-last-child(n) 的区别前者是从前往后计算,后者从后往前计算

11.表单选择器

例如:$('input:radio')

12.this

js中的this

var imooc = {    name:"慕课网",    getName:function(){        //this,就是imooc对象        return this.name;    }}imooc.getName(); //慕课网
jQuery中的$this

$('p').click(function(){    //把p元素转化成jQuery的对象    var $this= $(this)     $this.css('color','red')})

13.attr()和removeAttr()

  1. attr(传入属性名):获取属性的值
  2. attr(属性名, 属性值):设置属性的值
  3. attr(属性名,函数值):设置属性的函数值
  4. attr(attributes):给指定元素设置多个属性值,即:{属性名一: “属性值一” , 属性名二: “属性值二” , … … }
    <form>        <input type="text" value="设置value" />        <input type="text" value="获取value"/>        <input type="text" value="回调拼接value" />        <input type="text" value="删除value" />    </form>    <script type="text/javascript">    //找到第一个input,通过attr设置属性value的值    $('input:first').attr('value','原本的设置value会变成现在输入的内容');        $('input:eq(3)').removeAttr('value');  //删除第四个value中的值 </script> 简单来说attr是用来修改html标签属性的!!!!
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <style>        input {            display    : block;            margin     : 10px;            padding    : 10px;            background : #bbffaa;            border     : 1px solid #ccc;        }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body><h2>.attr()与.removeAttr()</h2><h3>.attr</h3><form>    <input type="text" value="设置value" />    <input type="text" value="获取value"/>    <input type="text" value="回调拼接value" />    <input type="text" value="删除value" /></form><script>     $('input:first').attr('value','哈哈哈');           var $val =  $('input:eq(1)').attr('value');     console.log($val);                $('input:eq(2)').attr('value',function (i,val) {          return '通过function设置的属性'+val;//文本内容变成   :通过function设置的属性回调拼接value      });         $('input:eq(3)').removeAttr('value')</script></body></html>

14.获取内容-text()、html()、val()

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>    <style>        div{            margin: 5px;        }        a{            display: block;        }    </style></head><body><h3>.html()与.text()</h3><div class="left first-div">    <div class="div">        <a>:first-child</a>        <a>第二个元素</a>        <a>:last-child</a>    </div>    <div class="div">        <a>:first-child</a>        <a>第二个元素</a>        <a>:last-child</a>    </div></div><h4>显示通过html方法获取到的内容</h4><p></p><h4>显示通过text方法获取到的内容</h4><p></p><script>   // $('p:first').text($('.first-div').html());//显示包括标签内容的整个结构 如下    //<div class="div"> <a>:first-child</a> <a>第二个元素</a> <a>:last-child</a> </div> <div class="div"> <a>:first-child</a> <a>第二个元素</a> <a>:last-child</a> </div>    //$('p:last').text($('.first-div').text());//只包括文本内容 没有标签 如下    //:first-child 第二个元素 :last-child :first-child 第二个元素 :last-child    //$('.first-div a:first').text('替换的文字');    //$('.first-div div:last a:first').text('第二个div的第一个a');  // $('.first-div div:first').html('替换整个div子节点')   $(".left a:first").text(function(idnex,text){       return '增加新的文本内容' + text// 文本内容为    :增加新的文本内容:first-child   })</script></body></html>总结:1.html(),.text(),.val()三种方法都是用来读取选定元素的内容;只不过.html()是用来读取元素的html内容(包括html标签),.text()用来读取元素的纯文本内容,包括其后代元素,.val()是用来读取表单元素的"value"值。其中.html()和.text()方法不能使用在表单元素上,而.val()只能使用在表单元素上;2..html()方法使用在多个元素上时,只读取第一个元素;.val()方法和.html()相同,如果其应用在多个元素上时,只能读取第一个表单元素的"value"值,但是.text()和他们不一样,如果.text()应用在多个元素上时,将会读取所有选中元素的文本内容。3..html(htmlString),.text(textString)和.val(value)三种方法都是用来替换选中元素的内容,如果三个方法同时运用在多个元素上时,那么将会替换所有选中元素的内容。
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <style>        p {            color: red;            margin: 4px;        }        b {            color: blue;        }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body><select id="single">    <option>慕课网</option>    <option>博客园</option></select><select id="multiple" multiple="multiple">    <option selected="selected">imooc</option>    <option >慕课网</option>    <option selected="selected">博客园</option></select><input type="text" value="click a button" /><p></p><script>  // $('p').text($('#single').val());//慕课网    $('p').text($('#multiple').val())//imooc   博客园  带有selected属性的被显示出来    $('input[type ="text"]').val('修改的内容');</script></body></html>


15.addClass()  removeClass()

不会替换样式名 而是在后面加一个样式

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    .left,    .right {        width: 300px;        height: 120px;    }        .left div,    .right div {        width: 100px;        height: 90px;        padding: 5px;        margin: 5px;        float: left;        border: 1px solid #ccc;    }            .newClass{        background: #bbffaa;    }    .imoocClass{        background: red;    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>.addClss()方法</h2>    <div class="left">        <div class="aaron">            <p>newClass</p>        </div>        <div class="aaron">            <p>newClass</p>        </div>    </div>    <div class="right">        <div class="aa bb imooc">            <article>                <p>imoocClass</p>            </article>        </div>        <div class="bb cc imooc ">            <article>                <p>imoocClass</p>            </article>        </div>    </div>    <script type="text/javascript">         //class=left下div元素增加一个新的样式,增加背景颜色        $('.left div').addClass('newClass')    </script>    <script type="text/javascript">             //通过className(fucntion)方法        //这个函数返回一个或更多用空格隔开的要增加的样式名。        //接收index 参数表示元素在匹配集合中的索引位置和html 参数表示元素上原来的 HTML 内容        //找到所有的div,然后通过addClass设置颜色,根据返回的className的判断,       $("div").addClass(function(index,className) {            //找到类名中包含了imooc的元素            if(-1 !== className.indexOf('imooc')){                //this指向匹配元素集合中的当前元素                $(this).addClass('imoocClass')            }        });    </script></body></html>


removeClass

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    .left,    .right {        width: 300px;        height: 120px;    }        .left div,    .right div {        width: 100px;        height: 90px;        padding: 5px;        margin: 5px;        float: left;        border: 1px solid #ccc;    }            .newClass{        background: #bbffaa;    }    .imoocClass{        background: red;    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>.removeClass()方法</h2>    <div class="left">        <div class="aaron newClass">            <p>newClass</p>        </div>        <div class="aaron newClass">            <p>newClass</p>        </div>    </div>    <div class="right">        <div class="aa bb imoocClass">            <article>                <p>imoocClass</p>            </article>        </div>        <div>            <article>                <p>imoocClass</p>            </article>        </div>    </div>    <script type="text/javascript">         //class=left下div元素删除newClass样式        $('.left div').removeClass('newClass')    </script>    <script type="text/javascript">         //.removeClass() 方法允许我们指定一个函数作为参数,返回将要被删除的样式        $('.right > div:first').removeClass(function(index,className){                        //className = aa bb imoocClass            //把div的className赋给下一个兄弟元素div上作为它的class            $(this).next().addClass(className)            //删除自己本身的imoocClass            return 'imoocClass'        })    </script></body></html>

最后一个函数将当前div的class给下一个兄弟节点!!!!!!


16.切换样式.toggleClass()

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title>    <style type="text/css">        body,        table,        td        {            font-family: Arial, Helvetica, sans-serif;            font-size: 12px;        }        .h {            background: #f3f3f3;            color: #000;        }        .c {            background: #ebebeb;            color: #000;        }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body><table id="table" width="50%" border="0" cellpadding="3" cellspacing="1">    <tr>        <td>慕课jQuery入门</td>        <td>慕课jQuery入门</td>    </tr>    <tr>        <td>慕课jQuery入门</td>        <td>慕课jQuery入门</td>    </tr>    <tr>        <td>慕课jQuery入门</td>        <td>慕课jQuery入门</td>    </tr>    <tr>        <td>慕课jQuery入门</td>        <td>慕课jQuery入门</td>    </tr>    <tr>        <td>慕课jQuery入门</td>        <td>慕课jQuery入门</td>    </tr></table><script type="text/javascript">    //给所有的tr元素加一个class="c"的样式    $("#table tr").toggleClass("c");</script><script type="text/javascript">    //给所有的偶数tr元素切换class="c"的样式    //所有基数的样式保留,偶数的被删除    $("#table tr:odd").toggleClass("c");</script><script type="text/javascript">    //第二个参数判断样式类是否应该被添加或删除    //true,那么这个样式类将被添加;    //false,那么这个样式类将被移除    //所有的奇数tr元素,应该都保留class="c"样式    $("#table tr:even").toggleClass("c", true); //这个操作没有变化,因为样式已经是存在的</script></body></html>
总结:toggleClass是一个互斥的逻辑,也就是通过判断对应的元素上是否存在指定的Class名,如果有就删除,如果没有就增加17 data()

向元素附加数据,然后取回该数据:

<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){  $("#btn1").click(function(){    $("div").data("greeting", "Hello World");  });  $("#btn2").click(function(){    alert($("div").data("greeting"));  });});</script></head><body><button id="btn1">把数据添加到 div 元素</button><br /><button id="btn2">获取已添加到 div 元素的数据</button><div></div></body></html>
先点第一个按钮将数据添加 再点第二个会alert出来

如果直接点第二个会显示undefined

18.jQuery节点创建与属性处理

$("<div class='right'><div class='aaron'>动态创建DIV元素节点</div></div>")

19.内部插入append() 和appendTo()在元素结尾插入   内部插入 prepend( ) prependTo()在元素之前插入

append()前面是被插入的对象,后面是要在对象内插入的元素内容appendTo()前面是要插入的元素内容,而后面是被插入的对象

20.外部插入before() after()

 <style>    .aaron{        border: 1px solid red;    }    </style></head><body>    <h2>通过before与after添加元素</h2>    <button id="bt1">点击通过jQuery的before添加元素</button>    <button id="bt2">点击通过jQuery的after添加元素</button>    <div class="aaron">        <p class="test1">测试before</p>    </div>    <div class="aaron">        <p class="test2">测试after</p>    </div>    <script type="text/javascript">    $("#bt1").on('click', function() {        //在匹配test1元素集合中的每个元素前面插入p元素        $(".test1").before('<p style="color:red">before,在匹配元素之前增加</p>', '<p style="color:red">多参数</p>')    })    </script>    <script type="text/javascript">    $("#bt2").on('click', function() {        //在匹配test1元素集合中的每个元素后面插入p元素        $(".test2").after('<p style="color:blue">after,在匹配元素之后增加</p>', '<p style="color:blue">多参数</p>')    })    </script></body>

before after都是为元素添加相邻的兄弟节点

支持多个参数


21.节点删除empty()  remove() detach()

<div class="hello"><p>慕课网</p></div>
//通过empty处理$('.hello').empty()//结果:<p>慕课网</p>被移除<div class="hello"></div>
//但是class=hello的div并没有被删去 只删除了内部节点


<div class="hello"><p>慕课网</p></div>$('.hello').on("click",fn)//绑定点击事件

//通过remove处理$('.hello').remove()//结果:<div class="hello"><p>慕课网</p></div> 全部被移除//节点不存在了,同时事件也会被销毁


detach为jQuery特有 所以绑定事件必须通过jQuery方法

如果我们希望临时删除页面上的节点,但是又不希望节点上的数据与事件丢失,并且能在下一个时间段让这个删除的节点显示到页面,这时候就可以使用detach方法来处理



22.节点的复制 clone() 替换replaceWith()  replaceAll()

HTML部分<div></div>JavaScript部分$("div").on('click', function() {//执行操作})//clone处理一$("div").clone()   //只克隆了结构,事件丢失//clone处理二$("div").clone(true) //结构、事件与数据都克隆
<div>    <p>第一段</p>    <p>第二段</p>    <p>第三段</p></div>
//替换第二段的内容
$("p:eq(1)").replaceWith('<a style="color:red">替换第二段的内容</a>')

 a.with.b 就是a被b替换
 b.all.a 就是b把a替换

23.包裹wrap()

简单的看一段代码:

<p>p元素</p>

给p元素增加一个div包裹

$('p').wrap('<div></div>')

最后的结构,p元素增加了一个父div的结构

<div>    <p>p元素</p></div>

unwrap()

<div>    <p>p元素</p></div>
$('p').unwrap();

找到p元素,然后调用unwrap方法,这样只会删除父辈div元素了

结果:

<p>p元素</p>

wrapAll()

简单的看一段代码:

<p>p元素</p><p>p元素</p>

给所有p元素增加一个div包裹

$('p').wrapAll('<div></div>')

最后的结构,2个P元素都增加了一个父div的结构

<div>    <p>p元素</p>    <p>p元素</p></div>
$('p').wrapAll(function() {    return '<div><div/>'; })

以上的写法的结果如下,等同于wrap的处理了

<div>    <p>p元素</p></div><div>    <p>p元素</p></div>

发现这个示例里的多个p标签如果不是连续的话(指多个p标签中前掺插了其他标签),会将非p标签的统一移动到p标签后面,然后再给p标签统一添加唯一的div父元素


wrapInner()

<div>p元素</div><div>p元素</div>

给所有元素增加一个p包裹

$('div').wrapInner('<p></p>')

最后的结构,匹配的di元素的内部元素被p给包裹了

<div>    <p>p元素</p></div><div>    <p>p元素</p></div>


24.遍历

children()

<body>    <h2>children方法()</h2>    <div class="left first-div">        <div class="div">            <ul class="level-1">                <li class="item-1">1</li>                <li class="item-2">2</li>                <li class="item-3">3</li>            </ul>        </div>        <div class="div">            <ul class="level-2">                <li class="item-1">1</li>                <li class="item-2">2</li>                <li class="item-3">3</li>            </ul>        </div>        <div class="div">            <ul class="level-3">                <li class="item-1">1</li>                <li class="item-2">2</li>                <li class="item-3">3</li>            </ul>        </div>    </div>    <button id="bt1">点击:children无参数</button>    <button id="bt2">点击:children传递表达式</button>    <script type="text/javascript">    $("#bt1").click(function() {        $('.div').children().css('border','3px solid red');//?    })    </script>    <script type="text/javascript">    $("#bt2").click(function() {        //找到所有class=div的元素        //找到其对应的子元素ul,然后筛选出最后一个,给边宽加上颜色        $('.div').children(':last').css('border', '3px solid blue')    })    </script>

find() children与find方法的区别,children是父子关系查找,find是后代关系(包含父子关系)

parent()                         因为是父元素,这个方法只会向上查找一级

parents()                        parent只会查找一级,parents则会往上一直查到查找到祖先节点

closet()   向上查找 如

$("div").closet("li')
.closest(),首先从本身开始向上匹配,若匹配到符合要求的第一个,即停止匹配。
.parents(),从元素父级一直向上匹配,找出所有匹配的符合要求元素。



next( )  想快速查找指定元素集合中每一个元素紧邻的后面同辈元素的元素集合,此时可以用next()方法

prev()如果想快速查找指定元素集合中每一个元素紧邻的前面同辈元素的元素集合,此时可以用prev()方法

sibilings()如果想快速查找指定元素集合中每一个元素的同辈元素,此时可以用siblings()方法

add( )  

例子:同时选择两个id对象
当用jQuery要选择demo1标签时,会用到下面代码:$('#demo1");
当用jQuery选择demo1和demo2,不要告诉我用$('div')。
这时就要用到标题中提到的方法,jQuery add方法:追加标签。

代码如下
$('#demo1").add('#demo2");



each()


each是一个for循环的包装迭代器each通过回调的方式处理,并且会有2个固定的实参,索引与元素each回调方法中的this指向当前迭代的dom元素
<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){  $("button").click(function(){    $("li").each(function(){      alert($(this).text())  //注意这里的$(this)    });  });});</script></head><body><button>输出每个列表项的值</button><ul><li>Coffee</li><li>Milk</li><li>Soda</li></ul></body></html>

结果:点击依次返回每个li的值




25.鼠标事件

click单击  dblclick双击

<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){  $("button").click(function(){    $("p").slideToggle();  });});</script></head><body><p>这是一个段落。</p><button>切换</button></body></html>


<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){  $("button").dblclick(function(){    $("p").slideToggle();  });});</script></head><body><p>这是一个段落。</p><button>请双击此处</button></body></html>

mouseup鼠标离开触发

mousedown鼠标按下触发

mousemove在指定元素内移动触发

<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){  $(document).mousemove(function(e){    $("span").text(e.pageX + ", " + e.pageY);  });});</script></head><body><p>鼠标位于坐标: <span></span>.</p></body></html>

mouseover  mouseout 当鼠标移到指定的元素上  离开指定的元素触发   两者配合使用

<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){  $("p").mouseover(function(){    $("p").css("background-color","yellow");  });  $("p").mouseout(function(){    $("p").css("background-color","#E9E9E4");  });});</script></head><body><p style="background-color:#E9E9E4">请把鼠标指针移动到这个段落上。</p></body></html>

mouseenter和mouseleave   和上述两组类似

区别在于

 $("li").each(function(i) {            //删除的鼠标划过的显示与隐藏            $(this).mouseover(function() {                $(this).find(".del").fadeIn(10);            })            $(this).mouseleave(function() {                $(this).find(".del").fadeOut(10);            })        })


上面的代码中如果不是用的mouseleave而是mouseout的话你会发现尚未离开类名的.del这个DIV这个DIV有时候就会闪动。那是因为你可能离开了该DIV的子元素,所以会出发mouseout事件。具体mouseleave和mouseout两者之间的区别主要有以下两点:

1.不论鼠标指针离开被选元素还是任何子元素,都会触发 mouseout 事件。

2.只有在鼠标指针离开被选元素时,才会触发 mouseleave 事件。

hover 其实是封装了mouseenter和mouseout

<!DOCTYPE html><html><head><meta charset="utf-8"><title>菜鸟教程(runoob.com)</title><script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script><script>$(document).ready(function(){  $("p").hover(function(){    $("p").css("background-color","yellow");    },function(){    $("p").css("background-color","pink");  });});</script></head><body><p>鼠标移动到该段落。</p></body></html>

focusin鼠标获得焦点事件

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    .left div,    .right div {        width: 500px;        height: 50px;        padding: 5px;        margin: 5px;        float: left;        border: 1px solid #ccc;    }    .left div {        background: #bbffaa;    }        .right div {        background: yellow;    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>.focusin()方法</h2>    <div class="left">        <div class="aaron">            点击聚焦:<input type="text" />        </div>    </div>    <div class="right">        <div class="aaron1">            点击聚焦并传递参数:<input type="text" />        </div>    </div>    <script type="text/javascript">        //input聚焦        //给input元素增加一个边框        $("input:first").focusin(function() {             $(this).css('border','2px solid red')        })    </script>    <script type="text/javascript">        //不同函数传递数据    $("input:last").focusin('慕课网', function(e) {         $(this).val(e.data);     })    </script></body></html>


focusout鼠标失焦事件 用法和上相同

下面这个例子可以区分

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    .left div,    .right div {        width: 500px;        height: 50px;        padding: 5px;        margin: 5px;        float: left;        border: 1px solid #ccc;    }        .left div {        background: #bbffaa;    }        .right div {        background: yellow;    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h4>.focusin与blur</h4>    <div class="left">        <div class="aaron">            点击触发焦点(无反应):            <input type="text" />        </div>        <div class="aaron1">            点击触发焦点并冒泡:            <input type="text" />        </div>    </div>    <script type="text/javascript">    $(".aaron").focus(function() {        $(this).css('border', '2px solid red')    })    $(".aaron1").focusin(function() {        $(this).find('input').val('冒泡捕获了focusin事件')    })    </script>    <h4>.focusout与blur</h4>    <div class="right">        <div class="aaron3">            点击触发失去焦点(无反应):            <input type="text" />        </div>        <div class="aaron4">            点击触发失去焦点并冒泡:            <input type="text" />        </div>    </div>    <script type="text/javascript">    $(".aaron3").blur(function() {        $(this).css('border', '2px solid red')    })    $(".aaron4").focusout(function() {        $(this).find('input').val('冒泡捕获了focusout事件')    })    </script></body></html>


你们看focus和blur事件都绑到了div上,你点击input或者点完移开失去焦点当然没反应了,因为input没有绑定事件啊。
而focusin和focuout也绑在div上,为啥有反应呢?
因为后者在你点input的时候会一级一级的往上面查父元素,如果父元素有事件就执行了,所以你看到了效果。这叫事件冒泡。
为啥前者不行呢?因为前者不支持事件冒泡。


26.表单事件

change事件

<input>元素,<textarea>和<select>元素的值都是可以发生改变的,开发者可以通过change事件去监听这些改变的动作

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    .left div,    .right div {        width: 100%;        padding: 5px;        margin: 5px;        float: left;        border: 1px solid #ccc;    }        .left div {        background: #bbffaa;    }        .right div {        background: yellow;    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>input、textarea与select</h2>    <div class="left">        <div class="aaron">input:            <input class="target1" type="text" value="监听input的改变" />        </div>        <div class="aaron1">select:            <select class="target2">                <option value="option1" selected="selected">Option 1</option>                <option value="option2">Option 2</option>            </select>        </div>        <div class="aaron3">textarea:            <textarea class="target2" rows="3" cols="20">多行的文本输入控件</textarea>        </div>    </div>    输出结果:    <div id="result"></div>    <script type="text/javascript">        //监听input值的改变    $('.target1').change(function(e) {        $("#result").html(e.target.value)    });    //监听select:    $(".target2").change(function(e) {        $("#result").html(e.target.value)    })     //监听textarea:    $(".target3").change(function(e) {        $("#result").html(e.target.value)    })    </script></body></html>
input和textarea鼠标 是去焦点后才触发change  option只要选择改变后立刻触发

select事件

当 textarea 或文本类型的 input 元素中的文本被选择时,会发生 select 事件。

select() 方法触发 select 事件,或规定当发生 select 事件时运行的函数。

例如

<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){  $("input").select(function(){    $("input").after(" Text marked!");  });});</script></head><body><input type="text" name="FirstName" value="Hello World" /><p>请试着选取输入域中的文本,看看会发生什么。</p></body></html>

submit事件 当提交表单时,会发生 submit 事件。

<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){  $("form").submit(function(e){    alert("Submitted");  });});</script></head><body><form name="input" action="" method="get">First name: <input type="text" name="FirstName" value="Mickey" size="20"><br />Last name: <input type="text" name="LastName" value="Mouse" size="20"><br /><input type="submit" value="Submit"></form> </body></html>

27.键盘事件

keydown()与keyup()事件  按下/松手英文字母触发

<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){  $("input").keydown(function(){    $("input").css("background-color","#FFFFCC");  });  $("input").keyup(function(){    $("input").css("background-color","#D6D6FF");  });});</script></head><body>Enter your name: <input type="text" /><p>当发生 keydown 和 keyup 事件时,输入域会改变颜色。请试着在其中输入内容。</p></body></html>


keypress

与 keydown 事件不同,每插入一个字符,就会发生 keypress 事件。

<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">i=0;$(document).ready(function(){  $("input").keypress(function(){    $("span").text(i+=1);  });});</script></head><body>Enter your name: <input type="text" /><p>Keypresses:<span>0</span></p></body></html>


27.事件的绑定与解绑

jquery为多个选择器绑定同一个事件

$("#start,#end").on("click",function(){    alert("The paragraph was clicked.");            });
多个事件绑定同一个函数

$("p").on("mouseover mouseout",function(){    $("p").toggleClass("intro");});
多个事件绑定不同函数

$("p").on({    mouseover:function(){$("body").css("background-color","lightgray");},      mouseout:function(){$("body").css("background-color","lightblue");},     click:function(){$("body").css("background-color","yellow");}    });



on的高级用法   事件委托

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    .left div,    .right div {        width: 500px;        height: 50px;        padding: 5px;        margin: 5px;        float: left;        border: 1px solid #ccc;    }        .left div {        background: #bbffaa;    }        .right div {        background: yellow;    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>on事件委托</h2>    <div class="left">        <div class="aaron">            <a>点击这里</a>        </div>    </div>    <script type="text/javascript">    //给body绑定一个click事件    //没有直接a元素绑定点击事件    //通过委托机制,点击a元素的时候,事件触发    $('body').on('click', 'a', function(e) {       alert(e.target.textContent)    })    </script></body></html>

本来事件绑定在body上,点a会冒泡到body,但指定了第二个参数是a,也就不往上冒了。


off()移除之前用on绑定的事件

处理函数才会被移除

绑定2个事件

$("elem").on("mousedown mouseup",fn)

删除一个事件

$("elem").off("mousedown")

删除所有事件

$("elem").off("mousedown mouseup")

快捷方式删除所有事件,这里不需要传递事件名了,节点上绑定的所有事件讲全部销毁

$("elem").off()


事件冒泡当你使用事件冒泡时,子级元素先触发,父级元素后触发,即p先触发,div后触发。<div id="divOne" onclick="alert('我是最外层');"><div id="divTwo" onclick="alert('我是中间层!')"><a id="hr_three" href="http://www.baidu.com" mce_href="http://www.baidu.com"onclick="alert('我是最里层!')">点击我</a></div></div>运行页面,点击“点击我”,会依次弹出:我是最里层---->我是中间层---->我是最外层---->然后再链接到百度.
28.事件属性

target 事件属性可返回事件的目标节点(触发该事件的节点),如生成事件的元素、文档或窗口。

语法

event.target


event.type  返回当前触发事件的事件类型 string类型

<div id="n1" style="height:100px; border: 1px solid #999;" ></div><input id="n2" name="uname" type="text" /><span id="msg"></span>与event.type属性相关的jQuery示例代码如下(其中表单验证部分的代码仅作简单的非空验证):// 为n1绑定mouseenter和mouseleave事件// 鼠标移入时,边框变为蓝色;鼠标移出时,边框变为原来的颜色(#999)$("#n1").bind("mouseenter mouseleave", function(event){    if(event.type == "mouseenter"){        $(this).css("borderColor", "blue");    }else{        $(this).css("borderColor", "#999");    }});// 为文本框n2绑定focus和blur事件// 获取焦点时,显示相应的提示信息// 失去焦点时,进行表单验证,并显示相应的提示信息$("#n2").bind("focus blur", function(event){    var $msg = $("#msg");    if(event.type == "focus"){        $msg.html( '请输入用户名!' );        $msg.css("color", "blue");    }else{        if( !this.value ){            $msg.html( '用户名不能为空!' );            $msg.css("color", "red");        }else{            $msg.html( '输入正确!' );            $msg.css("color", "green");        }    }});

event.pageX 和 event.pageY:获取鼠标当前相对于页面的坐标 见前面鼠标事件例子

event.stopPropagation() 方法:阻止事件冒泡

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    .left div,    .right div {        width: 500px;        height: 100px;        padding: 5px;        margin: 5px;        float: left;        border: 1px solid #ccc;    }        .left div {        background: #bbffaa;    }        .right div {        background: yellow;    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h3>事件对象的属性与方法</h3>    <div class="left">        <div id="content">            外层div元素            <br />            <span style="background: silver;">内层span元素</span>            <br /> 外层div元素        </div>        <br />        <div id="msg"></div>    </div>    <script type="text/javascript">    //为 <span> 元素绑定 click 事件      $("span").click(function() {        $("#msg").html($("#msg").html() + "<p>内层span元素被单击</p>");    });    //为 Id 为 content 的 <div> 元素绑定 click 事件      $("#content").click(function(event) {        $("#msg").html($("#msg").html() + "<p>外层div元素被单击</p>");        event.stopPropagation(); //阻止事件冒泡      });    //为 <body> 元素绑定 click 事件      $("body").click(function() {        $("#msg").html($("#msg").html() + "<p>body元素被单击</p>");    });    </script></body></html>

event.preventDefault() 方法:阻止默认行为

这个用的特别多,在执行这个方法后,如果点击一个链接(a标签),浏览器不会跳转到新的 URL 去了。我们可以用 event.isDefaultPrevented() 来确定这个方法是否(在那个事件对象上)被调用过了


this和event.target的区别:

js中事件是会冒泡的,所以this是可以变化的,但event.target不会变化,它永远是直接接受事件的目标DOM元素;


29.自定义事件

trigger()函数用于在每个匹配元素上触发指定类型的事件

此外,你还可以在触发事件时为事件处理函数传入额外的参数。

使用该函数可以手动触发执行元素上绑定的事件处理函数,也会触发执行该元素的默认行为。

以表单元素<form>为例,使用trigger("submit")可以触发该表单绑定的submit事件,也会执行表单submit事件的默认行为——表单提交操作。


请参考下面这段初始HTML代码:<input id="btn1" type="button" value="点击1" /><input id="btn2" type="button" value="点击2" /><a id="a1" href="#">CodePlayer</a><div id="log"></div>首先,我们为上述button和<a>元素绑定事件,然后使用trigger()函数直接触发事件,相应的代码如下:var $log = $("#log");function handler( event, arg1, arg2 ){    var html = '<br>触发元素#' + this.id + '的[' + event.type +']事件,额外的函数参数为:' + arg1 + ', ' + arg2;    $log.append( html );}var $buttons = $(":button");// 为所有button元素的click事件绑定事件处理函数$buttons.bind( "click", handler );// 为所有a元素的click、mouseover、mouseleave事件绑定事件处理函数$("a").bind( "click mouseover mouseleave", handler );// 触发所有button的click事件$buttons.trigger("click"); /*(追加文本)触发元素#btn1的[click]事件,额外的函数参数为:undefined, undefined触发元素#btn2的[click]事件,额外的函数参数为:undefined, undefined*/$("#btn1").trigger("click", "CodePlayer");/*(追加文本)触发元素#btn1的[click]事件,额外的函数参数为:CodePlayer, undefined*/// arg1 = "张三", arg2 = 20$("a").trigger("mouseover", ["张三", 20 ] );/*(追加文本)触发元素#a1的[mouseover]事件,额外的函数参数为:张三, 20*/$("a").trigger("mouseleave", { name: "张三", age: 18 } );/*(追加文本)触发元素#a1的[mouseleave]事件,额外的函数参数为:[object Object], undefined*/运行代码(以下代码请自行复制到演示页面运行)trigger()函数还可以根据传入事件处理函数的Event对象,来触发对应的事件。var $btn1 = $("#btn1");// 为btn1元素的click事件绑定事件处理函数$btn1.bind( "click", function(event){    alert("click1");    });// 为btn1元素的click事件绑定事件处理函数// 如果传入了一个有效的额外参数,则再次触发click$btn1.bind( "click", function(event, arg1){    alert("click2");    if(arg1)        $(this).trigger( event );});// $btn1.trigger( "click" ); // 调用一次click1、调用一次click2$btn1.trigger( "click", true ); // 调用两次click1、调用两次click2此外,trigger()函数还可以只触发包含指定定命名空间的事件(1.4.3+才支持命名空间)。function A( event ){    alert( 'A' );}function B( event ){    alert( 'B' );}function C( event ){    alert( 'C' );}var $btn1 = $("#btn1");// 为btn1元素的click事件绑定事件处理函数$btn1.bind( "click.foo.bar", A );$btn1.bind( "click.test.foo", B );$btn1.bind( "click.test", C );// 触发btn1的click事件,不限定命名空间$btn1.trigger("click"); // 触发A、B、C// 触发btn1的包含命名空间foo的click事件$btn1.trigger("click.foo"); // 触发A、B// 触发btn1的包含命名空间test的click事件$btn1.trigger("click.test"); // 触发B、C// 触发btn1的同时包含命名空间foo和test的click事件$btn1.trigger("click.foo.test"); // 触发B


triggerhandle 不会触发默认事件 待补充....




30.隐藏与显示

.hide()中间参数可以为空 也可以"slow/fast"

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    .left div,    .right div {        width: 100%;        height: 50px;        padding: 5px;        margin: 5px;        float: left;        border: 1px solid #ccc;    }        .left div {        background: #bbffaa;    }        .right div {        background: yellow;    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>hide</h2>    <div class="left">        <h4>测试一</h4>        <div id="a1">hide操作</div>        <button>直接hide</button>        <script type="text/javascript">        //点击buttom1 直接隐藏        $("button:first").click(function() {            $("#a1").hide()        });        </script>        <h4>测试一</h4>        <div id="a2">hide动画操作</div>        <button>hide带动画</button>        <script type="text/javascript">        //点击buttom2 执行动画隐藏        $("button:last").click(function() {            $("#a2").hide({                duration: 3000,                complete: function() {                    alert('执行3000ms动画完毕')                }            })        });        </script>    </div></body></html>

show 显示元素

$('elem').hide(3000).show(3000)//隐藏和显示的动画
$("#a1").stop().hide(3000).show(3000)
//stop() 用于避免动画执行过程中反复触发


显示和隐藏切换  toggle

如果用到show和hide事先要判断display的状态 toggle就不用 如果隐藏就显示  显示就隐藏

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    div {        width: 500px;        height: 50px;        padding: 5px;        margin: 5px;        float: left;        border: 1px solid #ccc;    }        .left {        background: #bbffaa;    }        .right {        background: yellow;        display: none;    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>通过toggle切换显示与隐藏</h2>    <div class="left">显示到隐藏</div>    <div class="right">隐藏到显示</div>    <button>直接show-hide动画</button>    <button>直接hide-show动画</button>    <script type="text/javascript">    $("button:first").click(function() {        $(".left").toggle(3000)    });    </script>    <script type="text/javascript">    $("button:last").click(function() {        $(".right").toggle(3000)    });    </script></body></html>


下拉动画 slideDown

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    .left div,    .right div {        width: 100%;        height: 50px;        padding: 5px;        margin: 5px;        float: left;        border: 1px solid #ccc;        display: none;    }    .left div {        background: #bbffaa;    }        .right div {        background: yellow;    }    </style><script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head><body>    <h2>slideDown</h2>    <div class="left">        <h4>测试一</h4>        <div id="a1">hide-show</div>        <button>点击slideDown显示动画</button>    </div>        <script type="text/javascript">        //点击button        //执行3秒隐藏        //执行3秒显示        $("button:first").click(function() {            $("#a1").slideDown(3000)        });        </script>    <div class="right">        <h4>测试二</h4>        <div id="a2">hide-show</div>        <button>点击slideDown执行回调</button>    </div>        <script type="text/javascript">        //点击button        //执行3秒隐藏        //执行3秒显示        $("button:last").click(function() {            $("#a2").slideDown(3000,function(){                alert('动画执行结束')            })        });        </script></body></html>

上卷动画slideUp

上卷下拉切换slideToggle

   $("button").click(function() {
            $("#a1").slideToggle(3000)
        });


31.淡入淡出效果

fadeOut淡出

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>        p{            color:red;        }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>fadeOut</h2>    <p>测试文字淡入效果</p>    <p>慕课网,专注分享</p>    淡出的隐藏效果:    <select id="animation">        <option value="1">fadeOut( )</option>        <option value="2">fadeOut( "slow" )</option>        <option value="3">fadeOut( 3000 )</option>        <option value="4">fadeOut( 1000, complete )</option>        <option value="5">fadeOut( 1000, "linear" )</option>        <option value="6">fadeOut( options )</option>    </select>        </br></br>        <input id="btnFadeOut" type="button" value="点击淡出隐藏" />    <input id="btnShow" type="button" value="显示" />        <script type="text/javascript">    //【显示】按钮    $("#btnShow").click(function() {        $("p").show();    });    //【隐藏】按钮    $("#btnFadeOut").click(function() {        var v = $("#animation").val();        if (v == "1") {            $("p").fadeOut();        } else if (v == "2") {            $("p").fadeOut("slow");        } else if (v == "3") {            $("p").fadeOut(3000);        } else if (v == "4") {            $("p").fadeOut(2000, function() {                alert("隐藏完毕!");            });        } else if (v == "5") {            $("p").fadeOut(1000, "linear");        } else if (v == "6") {            $("p").fadeOut({                duration: 1000            });        }    });    </script></body></html>


fadeIn淡入

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    select{        width:100%;        height: 30px;    }    p {        color: red;        display: none;    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>fadeIn</h2>    <p>测试文字淡出效果</p>    <p>慕课网,专注分享</p>    选择:淡出的隐藏效果    </br>    </br>    <select id="animation">        <option value="1">fadeIn( )</option>        <option value="2">fadeIn( "slow" )</option>        <option value="3">fadeIn( 3000 )</option>        <option value="4">fadeIn( 2000, complete )</option>        <option value="5">fadeIn( 1000, "linear" )</option>        <option value="6">fadeIn( options )</option>    </select>    </br></br>    <input id="btnFadeIn" type="button" value="执行淡出效果" />    <input id="btnHide" type="button" value="点击隐藏" />    <script type="text/javascript">    //【显示】按钮    $("#btnFadeIn").click(function() {        var v = $("#animation").val();        if (v == "1") {            $("p").fadeIn();        } else if (v == "2") {            $("p").fadeIn("slow");        } else if (v == "3") {            $("p").fadeIn(3000);        } else if (v == "4") {            $("p").fadeIn(2000, function() {                alert("显示完毕!");            });        } else if (v == "5") {            $("p").fadeIn(1000, "linear");        } else if (v == "6") {            $("p").fadeIn({                duration: 1000            });        }    });    // 【隐藏】按钮    $("#btnHide").click(function() {        $("p").hide();    });    </script></body></html>

fadeToggle淡入淡出切换

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    p {        color: red;    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>fadeToggle</h2>    <p>测试文字淡入淡出切换效果</p>    <p>慕课网,专注分享</p>    淡入淡出的隐藏效果:    <select id="animation">        <option value="1">fadeToggle( )</option>        <option value="2">fadeToggle( "slow" )</option>        <option value="3">fadeToggle( 3000 )</option>        <option value="4">fadeToggle( 1000, complete )</option>        <option value="5">fadeToggle( 1000, "linear" )</option>        <option value="6">fadeToggle( options )</option>    </select>    <input id="btnFadeSwitch" type="button" value="点击切换显示/隐藏">    <script type="text/javascript">    //【切换显示/隐藏】按钮    $("#btnFadeSwitch").click(function() {        var v = $("#animation").val();        if (v == "1") {            $("p").fadeToggle();        } else if (v == "2") {            $("p").fadeToggle("slow");        } else if (v == "3") {            $("p").fadeToggle(3000);        } else if (v == "4") {            $("p").fadeToggle(1000, function() {                alert("切换完毕!");            });        } else if (v == "5") {            $("p").fadeToggle(1000, "linear");        } else if (v == "6") {            $("p").fadeToggle({                duration: 1000            });        }    });    </script></body></html>

可控淡出效果fadeTo

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <title></title>
    <style>
    p {
        color: red;
    }
    </style>
    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>

<body>
    <h2>fadeTo</h2>
    <p>测试文字透明度效果</p>
    <p>慕课网,专注分享</p>
    透明度的设置效果:
    <select id="animation">
        <option value="1">fadeTo( "slow" ,0.5 )</option>
        <option value="2">fadeTo( 1000 ,0.2 )</option>
        <option value="3">fadeTo( 1000 ,0.9 ,complete)</option>
    </select>
    <input id="btnFadeSwitch" type="button" value="点击切换显示/隐藏">
    <script type="text/javascript">
    //【切换显示/隐藏】按钮
    $("#btnFadeSwitch").click(function() {
        var v = $("#animation").val();
        if (v == "1") {
            $("p").fadeTo("slow", 0.5);
        } else if (v == "2") {
            $("p").fadeTo(1000, 0.2);
        } else if (v == "3") {
            $("p").fadeTo(1000, 0.9, function() {
                alert('完成')
            });
        }
    });
    </script>
</body>

</html>

32.toggle与slideToggle细节区别:

  • toggle:动态效果为从右至左。横向动作,toggle通过display来判断切换所有匹配元素的可见性
  • slideToggle:动态效果从下至上。竖向动作,slideToggle 通过高度变化来切换所有匹配元素的可见性
33.jQuery动画

animate比前面的简单动画效果来说可以精准控制样式属性

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    p {        color: red;    }    div{        width:200px;         height: 100px;         background-color: yellow;        color:red;    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>animate(上)</h2>    <p>慕课网,专注分享</p>    <div id="aaron">内部动画</div>    点击观察动画效果:    <select id="animation">        <option value="1">动画1</option>        <option value="2">动画2</option>        <option value="3">动画3</option>        <option value="4">动画4</option>    </select>    <input id="exec" type="button" value="执行动画">    <script type="text/javascript">    $("#exec").click(function() {        var v = $("#animation").val();        var $aaron = $("#aaron");        if (v == "1") {            // 数值的单位默认是px            $aaron.animate({                width  :300,                height :300            });        } else if (v == "2") {            // 在现有高度的基础上增加100px            $aaron.animate({                 width  : "+=100px",                 height : "+=100px"            });        } else if (v == "3") {            $aaron.animate({                fontSize: "5em"            }, 2000, function() {                alert("动画 fontSize执行完毕!");            });        } else if (v == "4") {            //通过toggle参数切换高度            $aaron.animate({                width: "toggle"            });        }     });    </script></body></html>

options参数

  • duration - 设置动画执行的时间
  • easing - 规定要使用的 easing 函数,过渡使用哪种缓动函数
  • step:规定每个动画的每一步完成之后要执行的函数
  • progress:每一次动画调用的时候会执行这个回调,就是一个进度的概念
  • complete:动画完成回调
<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    p {        color: red;    }        div {        width: 200px;        height: 100px;        background-color: yellow;        color: red;    }    a{        display: block    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>animate(下)</h2>    <p>慕课网,专注分享</p>    <div id="aaron">内部动画</div>    点击观察动画效果:    <select id="animation">        <option value="1">动画step动画</option>        <option value="2">动画progress回调</option>    </select>    <a></a>    <input id="exec" type="button" value="执行动画">    <script type="text/javascript">    $("#exec").click(function() {        var v = $("#animation").val();        var $aaron = $("#aaron");        if (v == "1") {            //观察每一次动画的改变            $aaron.animate({                height: '50'            }, {                duration :2000,                //每一个动画都会调用                step: function(now, fx) {                   $aaron.text('高度的改变值:'+now)                }            })        } else if (v == "2") {            //观察每一次进度的变化            $aaron.animate({                height: '50'            }, {                duration :2000,                //每一步动画完成后调用的一个函数,                //无论动画属性有多少,每个动画元素都执行单独的函数                progress: function(now, fx) {                   $aaron.text('进度:'+arguments[1])                    // var data = fx.elem.id + ' ' + fx.prop + ': ' + now;                    // alert(data)                }            })        }     });    </script></body></html>


停止动画stop

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    p {        color: red;    }        div {        width: 200px;        height: 100px;        background-color: yellow;        color: red;    }    a{        display: block    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>stop</h2>    <p>慕课网,专注分享</p>    <div id="aaron">内部动画</div>    <input id="exec" type="button" value="执行动画"><br /><br />    点击观察动画效果:    <select id="animation">        <option value="1">stop()</option>        <option value="2">stop(true)</option>        <option value="3">stop(true,true)</option>    </select>    <a></a>    <input id="stop" type="button" value="停止动画">    <script type="text/javascript">    //点击执行动画    $("#exec").click(function(){        $("#aaron").animate({            height: 300        }, 5000)        $("#aaron").animate({            width: 300        }, 5000)        $("#aaron").animate({            opacity: 0.6        }, 2000)    })    $("#stop").click(function() {        var v = $("#animation").val();        var $aaron = $("#aaron");        if (v == "1") {            //当前当前动画            $aaron.stop()        } else if (v == "2") {            //停止所以队列            $aaron.stop(true)        } else if (v == "3") {            //停止动画,直接跳到当前动画的结束            $aaron.stop(true,true)        }     });    </script></body></html>

  1. stop():只会停止第一个动画,第二个第三个继续
  2. stop(true):停止第一个、第二个和第三个动画
  3. stop(true ture):停止动画,直接跳到第一个动画的最终状态

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    p {        color: red;    }        div {        width: 200px;        height: 100px;        background-color: yellow;        color: red;    }    a{        display: block    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>stop</h2>    <p>慕课网,专注分享</p>    <div id="aaron">内部动画</div>    <input id="exec" type="button" value="执行动画"><br /><br />    点击观察动画效果:    <select id="animation">        <option value="1">stop()</option>        <option value="2">stop(true)</option>        <option value="3">stop(true,true)</option>    </select>    <a></a>    <input id="stop" type="button" value="停止动画">    <script type="text/javascript">    //点击执行动画    $("#exec").click(function(){        $("#aaron").animate({            height: 300        }, 5000)        $("#aaron").animate({            width: 300        }, 5000)        $("#aaron").animate({            opacity: 0.6        }, 2000)    })    $("#stop").click(function() {        var v = $("#animation").val();        var $aaron = $("#aaron");        if (v == "1") {            //当前当前动画            $aaron.stop()        } else if (v == "2") {            //停止所以队列            $aaron.stop(true)        } else if (v == "3") {            //停止动画,直接跳到当前动画的结束            $aaron.stop(true,true)        }     });    </script></body></html>

34.each

回调函数中传入的两个参数,如果遍历的是数组,第一个参数是索引值,第二个参数是数组的值;如果遍历是对象,第一个参数是属性,第二个参数是属性值。

查找数组中的索引inArray

$.inArray(5,[1,2,3,4,5,6,7]) //返回对应的索引:4
有点像indexOf



trim去除字符串开始和结尾的空格  如果字符串中间存在空格 会被保留

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>trim方法</h2>    未处理    <input type="text" name="" id="results1" value=" 前后留空 " />    <input id="exec1" type="button" value="点击执行"> <br />        trim处理    <input type="text" name="" id="results2" value=" 前后留空 " />    <input id="exec2" type="button" value="点击执行">    <script type="text/javascript">    $("#exec1").click(function() {        alert("值的长度:" + $("#results1").val().length)    });    $("#exec2").click(function() {         alert("值的长度:" + $.trim($("#results2").val()).length)    });    </script></body></html>


get元素获取

jQuery是一个合集对象,如果需要单独操作合集中的的某一个元素,可以通过.get()方法获取到

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    a {               font-size: 30px;        font-weight: 900;    }        div {        width: 200px;        height: 100px;        background-color: yellow;        color: red;    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>get方法</h2>    <div id="aaron">        <a>1</a>        <a>2</a>        <a>3</a>        <a>4</a>        <a>5</a>    </div>    <select id="animation">        <option value="1">get正数索引参数</option>        <option value="2">get负数索引参数</option>    </select>    <input id="exec" type="button" value="点击执行">    <script type="text/javascript">    $("#exec").click(function() {        var v = $("#animation").val();        var $aaron = $("#aaron a");        //通过get找到第二个a元素,并修改蓝色字体        if (v == "1") {           $aaron.get(1).style.color = "blue"        } else if (v == "2") {            //通过get找到最后一个a元素,并修改字体颜色            $aaron.get(-1).style.color = "#8A2BE2"        }    });    </script></body></html>

如果你想改成eq()是可以的。但是你只把get()改成eq()是不行的。因为对$()用get(),那个$()所取到的元素就变成了dom,也就是变成了js。那么js取得的元素后面就必须跟js的方法或者属性,既$().get().style()。而不是$().get().css()。因为style是js独有的方法,而css()是jq独有的方法,get()方法后取得的js元素,它只能识别style(),而不能识别css()。


DOM元素的获取index方法

get方法是通过已知的索引在合集中找到对应的元素。如果反过来,已知元素如何在合集中找到对应的索引就要用index

<!DOCTYPE html><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title></title>    <style>    a {        font-size: 30px;        font-weight: 900;    }    </style>    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script></head><body>    <h2>index方法</h2>    <ul>        <a></a>        <a></a>        <li id="test1">1</li>        <li id="test2">2</li>        <li id="test3">3</li>    </ul>    <ul>        <li id="test4">4</li>        <li id="test5">5</li>        <li id="test6">6</li>    </ul>    <select id="animation">        <option value="1">index无参数</option>        <option value="2">index传递dom</option>        <option value="3">index传递jQuery对象</option>    </select>    <input id="exec" type="button" value="点击执行">    <br />    <br /> 索引结果:    <span></span>    <script type="text/javascript">    $("#exec").click(function() {        var v = $("#animation").val();        var $span = $("span");        $span.empty();        if (v == "1") {            //找到第一个li的同辈节点中的索引位置   返回2 同辈元素有前面两个a 所以第一个li是2            $span.text($("li").index())        } else if (v == "2") {            //通过传递dom查找  返回4            $span.text($("li").index(document.getElementById("test5")))        } else if (v == "3") {            //通过传递jQuery对象查找  返回5            $span.text($("li").index($("#test6")))        }    });    </script></body></html>