jQuery核心技術 (二)

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("服務器繁忙,請稍後重試");
                    }
                });
            });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章