jQuery核心技术 (二)

来源:互联网 发布:linux suse 11安装yum 编辑:程序博客网 时间:2024/06/05 00:52

jQuery教程

jQuery筛选

元素过滤

    eq(index|-index):             index:整数,从开头获得指定索引的元素。索引从0开始,0表示第一个            -index:负数,从尾部获得指定索引的元素。索引从-1开始,-1表示最后一个    first()     选择第一个元素     last()      选择最后一个元素     is()        用于判断     hasClass()  判断是否含有指定class。<xxx  class="xx">      filter()    筛选出指定表达式匹配的元素集合,返回符合一定条件的元素     not()       不符合条件的元素将从选择中返回,符合条件的元素将被移除     has()       返回拥有指定子元素的元素。     slice(start,end)  截取元素,包含头不包含尾 slice(2,4),则筛选23元素     map()        将jQuery对象拆分为jQuery对象数组。我们以前说过,jQuery内部是一个数组,用来存放获取的元素。这个方法将jQuery内部的元素分为一个个jQuery对象,将jQuery对象拆分为jQuery对象数组。 
例子1:        <script type="text/javascript">            $(document).ready(function(){                    $("#btn").click(function(){                        //选择索引为2的div,索引从0开始                        $("div").eq(2).css("background-color","red");                        //选择第一个div                        $("div").first().css("background-color","yellow");                        //选择最后一个div                        $("div").eq(-1).css("background-color","blue");                        });                 });        </script>        </head>        <body>                <div style="background:gray;width:100px;height:100px;"></div><br>                <div style="background:gray;width:100px;height:100px;"></div><br>                <div style="background:gray;width:100px;height:100px;"></div><br>                <div style="background:gray;width:100px;height:100px;"></div><br>                <input type="button" id="btn" value="按钮">        </body>
例子2:        <script type="text/javascript">            $(document).ready(function(){                    $("#btn").click(function(){                        //判断第一个div class属性是不是div1                        alert($("div").first().is(".div1"));                        //判断最后一个div class是否是div4                        alert($("div").last().hasClass("div4"));                        //选择含有p元素的div                        $("div").has("p").css("background-color","red");                    });                 });        </script>        </head>        <body>                <div style="background:gray;width:100px;height:100px;" class="div1"></div><br>                <div style="background:gray;width:100px;height:100px;"><p>China</p></div><br>                <div style="background:gray;width:100px;height:100px;"></div><br>                <div style="background:gray;width:100px;height:100px;" class="div4"></div><br>                <input type="button" id="btn" value="按钮">        </body>
例子3:        <script type="text/javascript">            $(document).ready(function(){                    $("#btn").click(function(){                        //筛选有class属性的div                        $("div").filter("[class]").css("background-color","red");                        //筛选没有class属性的div                        $("div").not("[class]").css("background-color","yellow");                      });                 });        </script>        </head>        <body>                <div style="background:gray;width:100px;height:100px;" class="div1"></div><br>                <div style="background:gray;width:100px;height:100px;"><p>China</p></div><br>                <div style="background:gray;width:100px;height:100px;"></div><br>                <div style="background:gray;width:100px;height:100px;" class="div4"></div><br>                <input type="button" id="btn" value="按钮">        </body>
例子4:        <script type="text/javascript">            $(document).ready(function(){                    $("#btn").click(function(){                        //截取第2.3个div                        $("div").slice(1,3).css("background-color","red");                    });                 });        </script>        </head>        <body>                <div style="background:gray;width:100px;height:100px;" class="div1"></div><br>                <div style="background:gray;width:100px;height:100px;"><p>China</p></div><br>                <div style="background:gray;width:100px;height:100px;"></div><br>                <div style="background:gray;width:100px;height:100px;" class="div4"></div><br>                <input type="button" id="btn" value="按钮">        </body>

元素查找

如有以下DOM树:    <A>        <B>            <C></C>            <D></D>            <E></E>            <F></F>        </B>    </A>    B.children([条件,可省略])     获得所有子元素  CDEF      A.find(D)                    查询指定后代元素    D     D.next()                     D同级的下一个   E     D.nextAll()                  D后面的所有同级 EF     E.prev()                     E同级的前一个     D     E.prevAll()                  E前面的所有同级 CD      E.siblings()                 E的所有同级  CDF     E.parent()                   获得父元素      B     E.cloest(A)                  向上获得指定的父元素     C.nextUntil(E)               获得后面的所有同级元素,直到指定位置。DE     F.prevUntil(D)               获得前面的所有同级元素,直到指定元素  DE     E.parents()                  获得所有的父元素  AB    
<script type="text/javascript">    $(document).ready(function(){            $("#btn").click(function(){                //获取所有子元素                //$("#div2").children().css("background-color","red");                //获取div1下的span2                //$("#div1").find("#span2").css("background-color","red");                //获取后面的所有兄弟元素,包括<br>等                //$("#span1").nextAll().css("background-color","red");                //获取父元素                $("#span1").parent().css("background-color","red");            });         });</script></head><body>        <div style="background:gray;width:100px;height:100px;" class="div1">            <div style="background:gray;width:100px;height:100px;" id="div2">                <span id="span1">第一句话</span><br>                <span id="span2">第二句话</span><br>                <span id="span3">第三句话</span>            </div>        </div><br>        <input type="button" id="btn" value="按钮"></body>

元素串联

        A.add(B)     将A和B组合一个对象         addBack()   把之前的元素添加到当前操作集合中。                    例如 A.children().andBack()  A自己本身也被添加到了子元素集合中        end         结束最近的一次筛选操作,并返回到前一次的状态。                    A.children().children().end(); 结束孙元素的集合,回到子元素的集合。        contends()  获取所有的子节点(子元素和文本)    
<script type="text/javascript">    $(document).ready(function(){            $("#btn").click(function(){                //将span1元素和span2元素结合                //$("#span1").add("#span2").css("background-color","red");                //将父元素div2也添加到当前操作集合                //$("#div2").children().addBack().css("background-color","red");                $("#div2").children().end().css("background-color","red");            });         });</script></head><body>        <div style="background:gray;width:100px;height:100px;" class="div1">            <div style="background:gray;width:100px;height:100px;" id="div2">                <span id="span1" style="background:yellow;"">第一句话</span><br>                <span id="span2">第二句话</span><br>                <span id="span3">第三句话</span>            </div>        </div><br>        <input type="button" id="btn" value="按钮"></body>

jQuery事件

    blur()          失去焦点     change()        选择改变时候触发事件,例如select列表     click()         单击     dbclick()       双击     focus()         获得焦点     keydown()       键盘按下的过程     keypress()      键盘按到底时     keyup()         键盘弹起     mousedown()     鼠标按下     mousemove()     鼠标移动     mouseout()      鼠标移出指定元素     mouseover()     鼠标移入指定元素        mouseup()       鼠标弹起     resize()        改变大小,例如窗体改变大小     scroll()        滚动条滚动     select()        选择     submit()        提交     unload()        页面卸载,页面关闭时     focusin()       获得焦点,跟focus区别在于,他可以在父元素上检测子元素获取焦点的情况                     例如父元素内部有一个子元素,当我们在子元素时,会触发fucusin。但是不会触发focus。     focusout()      失去焦点,跟blur事件区别在于,他可以在父元素上检测子元素失去焦点的情况。                    例如父元素内部有一个子元素,当我们子元素失去焦点时,会触发fucusout。但是不会触发blur。     mouseenter()    鼠标移入,跟mouseover事件不同,只有在鼠标指针移入被选元素时,才会触发mouseenter事件。如果鼠标穿过被选元素的子元素,不会触发,但是会触发mouseover事件。     mouseleave()    鼠标移出,跟mouseout事件不同,只有鼠标指针离开被选元素时,才会出发mouseleave事件。如果鼠标指针离开被选元素的子元素,不会触发,但是会触发mouseout事件  
常用事件例子:     <script type="text/javascript">        $(document).ready(function(){            $("#e01").blur(function(){                $("#textMsg").html("文本框失去焦点:blur");            }).focus(function(){                $("#textMsg").html("文本框获得焦点:focus");            }).keydown(function(){                $("#textMsg").append("键盘按下:keydown");            }).keypress(function(event){                $("#textMsg").append("键盘按下:keypress");            }).keyup(function(){                $("#textMsg").append("键盘按下:keyup");            });            //记录移动的次数            var i = 0;            $("#e02").mouseover(function(){                $("#divMsg").html("鼠标移上:mouseover");            }).mousemove(function(){                $("#divMsg").html("鼠标移动:mousemove , " + i++ );            }).mouseout(function(){                $("#divMsg").html("鼠标移出:mouseout");            }).mousedown(function(){                $("#divMsg").html("鼠标按下:mousedown");            }).mouseup(function(){                $("#divMsg").html("鼠标弹起:mouseup");            });            $("#e03").click(function(){                $("#buttonMsg").html("单击:click");            }).dblclick(function(){                $("#buttonMsg").html("双击:dblclick");            });        });    </script></head><body>    <input id="e01" type="text" /><span id="textMsg"></span> <br/>    <hr/>    <div id="e02" ></div><span id="divMsg"></span> <br/>    <hr/>    <input id="e03" type="button" value="可以点击"/><span id="buttonMsg"></span> <br/></body>
focus和focusin例子         <script type="text/javascript" src="jQuery/jquery-3.2.1.js"></script>            <script type="text/javascript">                $(document).ready(function(){                    //试试元素内部的子元素时聚焦时两个事件的不同                    $("#outerDiv").focusin(function(){                        alert("123");                    });                });            </script>        </head>        <body>            <div id="outerDiv" style="border:1px solid #f00;width:200px;height:200px">                <div id="innerDiv" style="border:1px solid #00f;width:100px;height:100px"></div>            </div>            <br/>            <span id="showSpan"></span>         </body>

事件处理

    bind(type,function) 给当前对象绑定一个事件。例如A.bind("click",function)     unbind(type)        解绑bind绑定事件     one(type,function)  给当前对象绑定一次事件。仅执行一次。     on(events,function) on() 方法在被选元素及子元素上添加一个或多个事件处理程序,on() 方法是 bind()live()delegate() 方法的新的替代品。     off(type)           off() 方法通常用于移除通过 on() 方法添加的事件处理程序,off() 方法是 unbind()die()undelegate() 方法的新的替代品       trigger(type)       在每一个匹配的元素上触发某类事件,会执行浏览器默认动作,会产生事件冒泡。A.trigger("submit");     hover(over,out)     简化版鼠标移入和移出
<script type="text/javascript">    $(document).ready(function(){            //给按钮1绑定一个事件            $("#btn1").bind("click",function(){                alert("123");            });             //给按钮2绑定一个事件,一点击就解绑按钮1的点击事件            $("#btn2").bind("click",function(){                $("#btn1").unbind("click");            });             //给按钮3绑定一次点击事件            $("#btn3").one("click",function(){                alert("只执行一次");            });    });</script></head><body>        <input type="button" id="btn1" value="按钮"><br>        <input type="button" id="btn2" value="按钮"><br>        <input type="button" id="btn3" value="按钮"></body>

jQuery效果

    show([speed],[function])        显示    hide([speed],[function])        隐藏。    toggle([speed],[function])      hide()show()方法之间切换    滑动    slideDown([speed],[function])   通过调整高度来滑动显示被选元素    slideUp([speed],[function]) 通过调整高度来滑动隐藏被选元素    slideToggle([speed],[function]) slideDown()slideUp()方法之间切换     淡入淡出    fadeIn(speed,callback)  淡出显示    fadeOut(speed,callback) 淡入隐藏    fadeToggle(speed,callback) fadeIn()fadeOut()方法之间切换     fadeTo(speed,opacity,callback) 允许渐变为指定的透明度。opacity指定透明度,在0与1之间    speed ,显示的时间,单位:毫秒。固定字符串"slow","normal","fast",function,callback都是回调函数。
<style type="text/css">        div{            border:1px solid #000;            width:100px;            height:100px;        }    </style>    <!-- 导入js库 ,注意:使用src属性之后,标签体中不能写入内容-->    <script type="text/javascript" src="jQuery/jquery-3.2.1.js"></script>    <script type="text/javascript">        $(document).ready(function(){            //点击按钮1是隐藏和显示               $("#b1").click(function(){                $("#b1Div").toggle("1000");            });            //点击按钮2,是滑动            $("#b2").click(function(){                $("#b2Div").slideToggle("slow");            });            //点击按钮3,是淡入淡出            $("#b3").click(function(){                $("#b3Div").fadeToggle("slow");            });            //点击按钮4,设定指定透明度            $("#b4").click(function(){                $("#b4Div").fadeTo("slow",0.25);            });        });    </script></head><body>    <input type="button" id="b1" value="显示/隐藏 b1Div" />    <div id="b1Div"></div> <br/>    <input type="button" id="b2" value="滑出/滑入b2Div"/>    <div id="b2Div"></div> <br/>    <input type="button" id="b3" value="淡出/淡入b3Div" />    <div id="b3Div"></div>    <input type="button" id="b4" value="设定指定的透明度b4Div" />    <div id="b4Div"></div></body>

jQuery AJAX

jQuery load()方法

        语法:$(selector).load(URL,data,callback);                 URL       请求的地址                data      请求参数                callback  回调参数        如果没有请求参数,发送GET请求。        如果有请求参数,发送POST请求。        回掉函数有三个参数,都可以省略。                -responseTxt - 服务器回应的数据,如果是中文,则必须在服务器端处理乱码                -statusTXT - 请求的状态。success或 error                -xhr - 包含 XMLHttpRequest 对象 
<script type="text/javascript">    $(document).ready(function(){             //点击按钮向服务器发送数据            $("#btn").click(function(){                //url                var url="/JsDemo/SendServlet";                //数据,json格式                var data={"username":"张三","password":"123456"};                $(this).load(url,data,function(responseTxt){                     //获取服务器回应的数据,并转换为json对象                    var jsonData=eval("("+responseTxt+")");                    alert(jsonData.message);                });            });    });</script></head><body>    <input type="button" value="发送" id="btn"></body>
SendServlet:         public class SendServlet extends HttpServlet {            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {                 //获取请求方式和请求参数                String method=request.getMethod();                String username=request.getParameter("username");                String password=request.getParameter("password");                System.out.println("请求方法:"+method);                System.out.println("username:"+username);                System.out.println("password:"+password);                //创建json数据并返回                String jsonData="{\"message\":\"成功\"}";                 //处理乱码                response.setContentType("application/json;charset=UTF-8");                response.getWriter().print(jsonData);            }            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {                doGet(request, response);            }        }

jQuery $.get()方法

$.get()    发送get请求            语法:jQuery.get(url, [data], [callback], [type])                 URL      请求的地址                data     请求参数                callback 回调参数                type     返回内容格式,xml, html, script, json, text,                 响应数据,如果设置  application/json;charset=UTF-8 自动将数据转换json对象。                响应数据,如果设置  text/html;charset=UTF-8 ,回调函数获得字符串数据,需要手动转换json对象。我们可以使用type设置"json",jQuery自动将字符串 转换成 json对象 
<script type="text/javascript">    $(document).ready(function(){            $("#btn").click(function(){                var url="/JsDemo/SendServlet";                var data={"username":"张三","password":"123456"};                //发送get请求                $.get(url,data,function(responseTxt){                    alert(responseTxt.message);                });            });    });</script></head><body>    <input type="button" value="发送" id="btn"></body>
SendServlet:         public class SendServlet extends HttpServlet {            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {                String method=request.getMethod();                String username=request.getParameter("username");                String password=request.getParameter("password");                System.out.println("请求方法:"+method);                System.out.println("username:"+username);                System.out.println("password:"+password);                String jsonData="{\"message\":\"成功\"}";                 response.setContentType("application/json;charset=UTF-8");                response.getWriter().print(jsonData);            }            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {                // TODO Auto-generated method stub                doGet(request, response);            }        }

jQuery $.post()方法

    $.post()   发送post请求    语法:jQuery.post(url, [data], [callback], [type])    和上面的一样,这里就不再给出例子。

jQuery $.ajax()方法

$.ajax()            底层的请求方法。上面的所有jQuery AJAX方法底层都是使用ajax()方法。            该方法通常用于其他方法不能完成的请求,功能强大。            语法:$.ajax({name:value, name:value, ... })              有很多的参数,我们可以参考文档。 
$("#btn").click(function(){                var url="/JsDemo/SendServlet";                var data={"username":"张三","password":"123456"};                $.ajax({                    "url":url,                    "data":data,                    "type":"POST",                    "success":function(data){                        alert(data);                    },                    "error":function(){                        alert("服务器繁忙,请稍后重试");                    }                });            });