jQuery
| 
 | 
 | 
##jQuery代码风格
- 链式操作风格
- 对于 同一个对象不超过3个操作,可以直接写成一行
| 
 | 
 | 
- 对于同一个对象的较多操作,建议每行写一个操作 12345$(this).removeClass("mouseout").addClass("mouseover").stop().fadeTo("fast".0.6).fadeTo("fast".1)
- 对于多个对象的少量操作,每个对象写一行,如果涉及子元素,可以考虑适当缩进 1234$(this).addClass("highlight").children("li").show().end().siblings().removeClass("highlight").children("li").hide();
- 为代码添加注释
 ##jQuery对象和DOM对象
- DOM对象
 通过js中的getElementsByTagName或者,getElementById来获取元素节点,像这样的到的就是DOM对象
- jQuery对象
 jQuery对象就是通过jQuery包装DOM对象后产生的对象,jQuery对象是jQuery独有的,如果一个对象是jQuery对象,那么就可以使用jQuery里面的方法123$("#foo").html();等价于document.getElementById("foo").innerHTML
`注意:
- 在jQuery对象中无法使用DOM对象的任何方法如:$(#id).innerHTML(错误)
- DOM对象也不能使用jQuery里面的方法
 如:document.getElementById(“id”).html()(错误)
 ###jQuery对象和DOM对象的相互转换
- 定义变量的风格
- jQuery对象
 var $variable=jQuery对象(在变量前面加上$)
- DOM对象
 var variable=DOM对象
- jQuery对象转化成DOM对象
 (1)jQuery对象那个是一个类似数组的对象,可以通过[index]的方法得到相应的DOM对象1234var $cr=$("#cr");//jQuery对象var cr=$cr[0];//DOM对象alert(cr.checked);//检测这个checkbox是否被选中了
(2)还可以通过jQuery本身提供的,通过get(index)方法得到相应的DOM对象
- DOM对象转成jQuery对象
 对于一个DOM对象,只要用$()把DOM对象包装起来,就可以获得一个jQuery对象了。方式为:$(DOM对象)123var cr=document.getElementById("cr");//DOM对象var $cr=$(cr);
注意:
- 转换后可以任意使用jQuery中方法
- 平时用到的jQuery对象都是通过$ ()函数制造出来的,$ ()函数就是一个jQuery对象的制造厂123456789101112131415161718$(document).ready(function(){var $cr=$("#cr");var cr=$cr[0];$cr.click(function(){if(cr.checked){alert("感谢你的支持!你可以继续操作了!");}})})//换成jQuery对象完成$(document).ready(function(){var $cr=$("#cr");$cr.click(function(){if($cr.is(":checked")){alert("感谢你的支持!你可以继续操作了1!");}})})
##解决jQuery与其他库的冲突注意:默认情况下,jQuery用$作为自身的快捷方式
- jQuery库在其他库之后导入
 在其他库和jQuery库被加载完毕后,可以在任何时候调用jQuery.noConflict()函数来将变量$的控制权转移给其他js库。
- 如果jQuery库在其他库之前就导入了,那么可以直接使用“jQuery”来做一些jQuery的工作,同时,可以使用$()方法作为其他库的快捷方式。这里无需jQuery.noConflict()函数。
 ##jQuery选择器
- css选择器
- jQuery选择器 123456<script type="text/javascript">$(".demo").click(function(){alert("jQuery选择器");})</script><p class="demo">jQuery Demo</p>
- jQuery选择器的优势 
- $()函数在很多js类库中都被作为一个选择器来使用。$(“#ID”)用来代替document.getElementById()函数。
- 支持css1到css3选择器
- 完善的处理机制
| 
 | 
 | 
注意:$(“#tt”)获取的永远是对象,即使网页没有此元素。因此当要用jQuery检查某个元素在网页上是否存在。
- jQuery基本选择器
 它通过元素id,class和标签名等来查找DOM元素
- 层次选择器 
 通过DOM元素之间的层次关系来获取特定元素。如:后代元素,子元素,相邻元素和同辈元素。
 可以使用next()方法来替代$(‘prev+next’)选择器
 $(‘.one+div’)等价于$(“.one”).next(“div”)
 $(“#prev~siblings”)等价于$(“#prev”).nextAll(“div”)12345//选取#prev之后的所有同辈div元素$("#prev~div").css("background","#eee");//同上$("#prev").nextAll("div").css("background","eee");//选取#prev所有的同辈div,无论前后位置
- 过滤选择器 
 基本过滤,内容过滤,可见性过滤,属性过滤,子元素过滤和表单对象属性过滤选择器
 :has(selector)选取含有选择器所匹配的元素的元素。$(“div:has(p)”)选取含有- 元素的 元素
- 选择器中含有”.” ,”#” ,”(“ ,”]”等特殊的字符 
 直接使用会出错,应该使用转义符转义12345678910<div id="id#b">bbb</div><div id="id[1]">ccc</div>普通方式获取:$("#id#b");$("#id[1]")以上错误$("#id\\#b");$("#id\\[1\\]");以上正确
- 属性选择器的@符号问题 
 jQuery在1.3.1版本中彻底放弃了1.1.0版本遗留下来的@符号,如果使用1.3.1以上版本,则不需要在属性签添加@符号
 如:
 $(“div[@title=’test’]”);
 正确写法是去除@符号
 $(“div[title=’test’]”);
- 选择器中含有空格的注意事项
 多一个空格或者少一个空格也许会得到截然不同的结果。
filter(expr):筛选出与指定表达式匹配的元素集合,其中expr可以是多个选择器的组合。
与find()的区别:find()会在匀速内寻找匹配的元素,而filter()则是筛选元素。一个是对它的子集操作,一个是对自身集合元素进行筛选。
##jQuery其他选择器
- jQuery提供的选择器扩展
- MoreSelectors for jQuery
- Basic XPath
- 其他使用css选择器的方法
- document.getElementBySelector()
- cssQuery()
- querySelectorAll()
 ##jQuery中的DOM操作
DOM是一种与浏览器,平台,语言无关的接口,使用该接口可以轻松的访问页面中所有的而标准组件。
###DOM操作分类
- DOM Core(核心)
 它并不专属于js
- HTML-DOM
- CSS-DOMjQuery中的DOM操作一. 查找节点
- 查找元素节点 12345var $li=$("ul li:eq(1)");//获取<ul>里面的第2个<li>节点var li_txt=$li.text();//获取元素节点的文本内容console.log(li_txt);
- 查找属性节点 
 attr()方法:当参数是一个时,则是要查找的属性的名字。123var $para=$("p");var p_txt=$para.attr("title");console.log(p_txt);
二. 创建节点
- 创建元素节点1234var $li_1=$("<li></li>");var $li_2=$("<li></li>");$("ul").append($li_1);$("ul").append($li_2);
注意:
- 动态的创建的的新元素节点不会被自动添加到文档中,而是要用方法插入到文档中
- 可以用 $(“< /p>”)或者 $(“< p> < /p>”)不能使用$(““)或者$(“< /P>”) 
- 创建文本节点 1234var $li_1=$("<li>文本节点</li>");var $li_2=$("<li>文本节点</li>");$("ul").append($li_1);$("ul").append($li_2);
- 创建属性节点 1234567891011121314var $li_1=$("<li title="标题1">文本节点</li>");var $li_2=$("<li title="标题2">文本节点</li>");$("ul").append($li_1);$("ul").append($li_2);```三.插入节点各种方法* append()/appendTo()* prepend()/prependTo()* after()/insertAfter()* before()/insertBefore()四. 删除节点1. remove()方法作用:是从DOM中删除所有匹配的元素,传入的参数是用于根据jQuery表达式来筛选元素
$(“ul li:eq(1)”).remove();
var $li=$(“ul li:eq(1)”).remove();
//将第2个
$li.appendTo(“ul”);
//把刚才删除的节点又重新添加到
- 中
| 
 | 
 | 
$(“ul li:eq(1)”).appendTo(“ul”);
$(“ul li”).remove(“li[title!=菠萝]”);
//删除title不为菠萝的li
var $li=$(“ul li:eq(1)”).detach();
//将第2个
$li.appendTo(“ul”);
//重新追加此元素,发现它之前的绑定的事件还在,如果使用remove(),那么它之前的绑定事件将失效
| 
 | 
 | 
$(“ul li:eq(1)”).empty();
//清空第2个li里的内容
$(“ul li”).click(function(){
    $(this).clone().appendTo(“ul”)
});
$(this).clone(true).appendTo(“body”);
| 
 | 
 | 
哈哈
$(“p”).replaceWith(“嗯嗯“);
| 
 | 
 | 
$(“嗯嗯“).replaceAll(“p”);
| 
 | 
 | 
$(“strong”).wrap(““);
得到如下:
| 
 | 
 | 
wrap():
$(“strong”).wrap(““);
得到如下:
1111
2222
wrapAll():
$(“strong”).wrapAll(““);
得到如下:
1111
2222
| 
 | 
 | 
$(“strong”).wrapInner(““);
结果如下:
你喜欢的水果是?
| 
 | 
 | 
获取属性:
var $para=$(“p”);
var p_txt=$para.attr(“title”);
设置属性:(注意传递两个参数)
$(“p”).attr({“title”:”your title”,”name”:”test”});
| 
 | 
 | 
$(“p”).removeAttr(“title”);
| 
 | 
 | 
$(“p”).attr(“class”,”high”);
变为:
追加class用addCalss()方法
$(“p”).addClass(“another”);
| 
 | 
 | 
删除class=”high”
$(“p”).removeClass(“high”);
删除多个class
$(“p”).removeClass(“high another”);
删除全部class
$(“p”).removeClass();
| 
 | 
 | 
$(“p”).toggleClass(“another”)
原样式与另一样式之间进行切换
$(“single”).val(“选择2号”);
$(“#multiple”).val([“选择2号”,”选择3号”);
$(“:checkbox”).val([“check2”,”check3”]);
$(“:radio”).val([“radio”]);
$(“p”).width();
//获取
元素的宽度值
$(“p”).width(“400px”);
//设置
元素的宽度值为400px
var offset=$(“p”).offset();
var left=offset.left;
vat top=offset.top;
var $p=$(“p”);
var scrollTop=$p.scrollTop();
var scrollLeft=$p.scrollLeft();
$(function(){
    $(“#panel h5.head”).toggle(function(){
$(this).addClass(“highlight”);
$(this).next().show();
},function(){
$(this).removeClass(“highlight”);
$(this).next().hide();
});
})
$(‘span’).bind(“click”,function(event){
                var txt=$(‘#msg’).html()+”
内层span元素被单击
“;$(“#msg”).html(txt);
event.stopPropagation();
//停止事件冒泡
});
| 
 | 
 | 
event.preventDefault();
//阻止默认行为                event.stopPropagation();
//停止事件的冒泡
// return false;(对上述阻止行为的简写)
//同时阻止默认行为,停止事件的冒泡
$("a").click(function(event){
        alert(event.type);
        return false;
    });
| 
 | 
 | 
$(“a[href=’http://google.com']).click(function(event){
    var tg=event.target;
    alert(tg.href);
    //http://google.com
    return false;
});
| 
 | 
 | 
$(“a”).mousedown(function(e){
                console.log(e.which);
                return false;
        });
$(“#delAll”).click(function(){
                $(“#btn”).unbind(“click”);
            });
| 
 | 
 | 
$(‘#btn’).bind(“click”,myFun1=function(){
$(‘#test’).append(“
我的绑定函数1
“);}).bind(“click”,myFun2=function(){
$(‘#test’).append(“
我的绑定函数2
“); }).bind(“click”,myFun3=function(){$(‘#test’).append(“
我的绑定函数3
“);});
| 
 | 
 | 
$(function(){                $(‘#btn’).bind(“myClick”,function(){
$(‘#test’).append(“
我的自定义事件
“);});
$(‘#btn’).trigger(“myClick”);
});
| 
 | 
 | 
$(function(){        $(‘#btn’).bind(“myClick”,function(event,message1,message2){
$(‘#test’).append(“
“+message1+message2+”
“);});
$(‘#btn’).trigger(“myClick”,[“我的”,”梦想”]);
});
| 
 | 
 | 
$(“input”).trigger(“focus”);
//以上代码不仅会触发元素绑定的focus事件,也会使元素本身得到焦点(这是浏览器的默认操作)
$(function(){
$(“.bg”).bind(“mouseover mouseout”,function(){
        $(this).toggleClass(“over”);
            });
        });
        相当与下面代码:
$(function(){
            $(“.bg”).bind(“mouseover”,function(){
                $(this).toggleClass(“over”);
            }).bind(“mouseout”,function(){
                $(this).toggleClass(“over”);
            });
        });
$(function(){
            $(“div”).bind(“click.plugin”,function(){
                $(“body”).append(“
click事件
“);});
$(“div”).bind(“mouseover.plugin”,function(){
$(“body”).append(“
mouseover事件
“);});
$(“div”).bind(“dbclick.plugin”,function(){
$(“body”).append(“
dbclick事件
“);});
$(“button”).click(function(){
$(“div”).unbind(“.plugin”);
});
| 
 | 
 | 
$(function(){
            $(“div”).bind(“click”,function(){
                $(“body”).append(“
click事件
“);});
$(“div”).bind(“click.plugin”,function(){
$(“body”).append(“
click.plugin事件
“);});
$(“button”).click(function(){
$(“div”).trigger(“click!”);
})
});
| 
 | 
 | 
$(“element”).hide();
等价于:
$(“element”).css(“display”,”none”);
$(function(){
            $(“#panel”).mouseover(function(){
                $(this).animate({left:”500px”},3000);
            });
        });
| 
 | 
 | 
$(this).animate({left:”+=500px”},3000);
$(“div”).click(function(){
 $(this).animate({left:”500px”,height:”200px”},3000);
});
$(this).animate({left:”500px”},3000);
$(this).animate({height:”500px”},3000);
$(“#panel”).css(“opacity”,”0.5”);
            $(“#panel”).click(function(){
                $(this).animate({left:”400px”,height:”200px”,opacity:”1”},3000)
                    .animate({top:”200px”,width:”200px”},3000,function(){
                        $(this).css(“border”,”5px solid green”);
                    })
                    // .fadeOut(“slow”);
                    //让元素最后隐藏消失
                    // .css(“border”,”5px solid green”);
                    //一开始动画就执行了,需要用回调函数,将css()放在动画队列里面
});
| 
 | 
 | 
if(!$(element).is(“:animated”)){
//判断元素是否处于动画状态
//如果当前没有进行动画,则添加新动画
}
/*input:focus,textarea:focus{
            border: 2px solid #f00;
            background: #fcc;
}*/
/*解决IE6不支持:focus伪类情况*/
.focus{
    border: 2px solid #f00;
    background: #fcc;
}
$(function(){
            $(“:input”).focus(function(){
                $(this).addClass(“focus”);
            }).blur(function(){
                $(this).removeClass(“focus”);
            });
        });
| 
 | 
 | 
// $(function(){
        //     var $comment=$(“#comment”);
        //     $(“.bigger”).click(function(){
        //         if($comment.height()<500){ $comment.height($comment.height()+50);="" }="" });="" $(".smaller").click(function(){="" if($comment.height()="">50){
        //             $comment.height($comment.height()-50);
        //         }
        //     });500){>
// });
//使用animate()有一种缓冲效果比起height()
$(function(){
    var $comment=$("#comment");
    $(".bigger").click(function(){
        if(!$comment.is(":animated")){
            if($comment.height()<500){
                $comment.animate({height:"+=50"},400);
            }
        }
    });
    $(".smaller").click(function(){
        if(!$comment.is(":animated")){
            if($comment.height()>50){
                $comment.animate({height:"-=50"},400);
            }
        }
    });
});
| 
 | 
 | 
$(function(){
            $(“#checkAll”).click(function(){
                $(‘[name=items]:checkbox’).attr(‘checked’,true);
            });
            $(“#checkNo”).click(function(){
                $(‘[name=items]:checkbox’).attr(‘checked’,false);
            });
            $(“#checkRev”).click(function(){
                $(‘[name=items]:checkbox’).each(function(){
                    // $(this).attr(“checked”,!$(this).attr(“checked”));
                    this.checked=!this.checked;
                });
            });
            $(“#send”).click(function(){
                var str=”你选中的是:\r\n”;
                $(‘[name=items]:checkbox:checked’).each(function(){
                    str+=$(this).val()+”\r\n”;
                });
                alert(str);
            });
        });
| 
 | 
 | 
$(function(){
        //     $(‘[name=items]:checkbox’).click(function(){
        //     var flag=true;
        //     $(‘[name=items]:checkbox’).each(function(){
        //         if(!this.checked){
        //             flag=false;
        //         }
        //     });
        //     $(‘#checkedAll’).attr(‘checked’,flag);
        // });
//另一种方法:判断复选框的总数是否与选中的复选框数量相等
$(‘[name=items]:checkbox’).click(function(){
    //定义一个临时变量,避免重复使用同一个选择器选择页面中的元素,提高程序效率
    var $tmp=$(‘[name=items]:checkbox’);
    //用filter()方法选出选中的复选框,直接给checkedAll赋值
    $(‘#checkedAll’).attr(‘checked’,$tmp.length==$tmp.filter(‘:checked’).length);
});
});
| 
 | 
 | 
$(function(){
            //从左到右
            $(‘#add’).click(function(){
                var $options=$(‘#select1 option:selected’);
                // var $remove=$options.remove();
                // $remove.appendTo(‘#select2’);
                //删除和追加可以直接用appendTo()方法完成
                $options.appendTo(‘#select2’);
            });
            $(‘#add_all’).click(function(){
                var $options=$(‘#select1 option’);
                $options.appendTo(‘#select2’);
            });
            $(‘#select1’).dblclick(function(){
                var $options=$(“option:selected”,this);
                $options.appendTo(‘#select2’);
            });
            //右到左
            $(‘#remove’).click(function(){
                var $options=$(‘#select2 option:selected’);
                // var $remove=$options.remove();
                // $remove.appendTo(‘#select2’);
                //删除和追加可以直接用appendTo()方法完成
                $options.appendTo(‘#select1’);
            });
            $(‘#remove_all’).click(function(){
                var $options=$(‘#select2 option’);
                $options.appendTo(‘#select1’);
            });
            $(‘#select2’).dblclick(function(){
                var $options=$(“option:selected”,this);
                $options.appendTo(‘#select1’);
            });
});
| 
 | 
 | 
| 
 | 
 | 
$(function(){
            // $(“tr:odd”).addClass(“odd”);
            // $(“tr:even”).addClass(“even”);
            // 除去表头的隔行变色
            $(“tbody>tr:odd”).addClass(“odd”);
            $(“tbody>tr:even”).addClass(“even”);
            //某一行高亮显示
            // $(“tr:contains(‘张珊5’)”).addClass(‘selected’);
            //单击单选按钮,进行高亮显示
        $(‘tbody>tr’).click(function(){
            $(this)
                .addClass(‘selected’)
                .siblings().removeClass(‘selected’)
                .end()
                //使用end()后.find(‘:radio’)就是$(this).find(‘:radio’)
                .find(‘:radio’).attr(‘checked’,true);
        });
        $(‘table :radio:checked’).parent().parent().addClass(‘selected’);
        //注意$(‘table :radio:checked’)中table与:radio间一定要有空格
//用parents()方法简化
$('table :radio:checked').parents("tr")addClass('selected');
//has()方法进一步简化代码
$('tbody>tr:has(:checked)').addClass("selected");
});
| 
 | 
 | 
$(function(){
            $(“#send”).click(function(){
                $(“#resText”).load(“test.html”);
            });
        });
    
| 
 | 
 | 
//只加载test.html页面中的class为para的内容
                $(“#resText”).load(“test.html .para”);
//无参数传递,则是get方式
$(“$resText”).load(“test.php”,function(){
});
//有参数传递,则是;post方式
$(“#resText”).load(“test.php”,{name:”rain”,age:”22” },function(){
});
$(“#resText”).load(“test.php”,function(responseText,textStatus,XMLHttpRequest){
//responseText请求返回的内容
//textStatus请求返回的状态
//XMLHttpRequest:XMLHttpRequest对象
});
###禁用缓存
问题:数据已经更新了,但传递的还是以前的数据
解决:应该禁用缓存
如果是$.post方法获取的数据,那么默认就是禁用缓存的,如果是$.get()方法,可以设置时间戳来避免缓存,可以在URL的后面加上+(+new Date)
(+new Date)的等价于new Date().getTime()
不用随机数的原因:因为随机数对于一台电脑来说,在大量使用之后出现重复的概率会很大,而时间戳不会。
如果是使用了$.ajax()方法来获取数据,只需要设置cache:false即可,注意:false是布尔值,而不是字符串。
