【鋒利的jQuery】中全局事件ajaxStart、ajaxStop不執行


最近一直都在研究【鋒利的jQuery】,確實是一本好書,受益匪淺。但由於技術發展及版本更新等原因,里面還是有些坑需要踩的。

比如:第六章七節中提到的全局事件ajaxStart、ajaxStop照着案例敲結果並不會執行。

在查閱資料后,發現原來在jquery1.9+版本以后,ajax全局事件需綁定到document對象上才能觸發。

下面是各版本不同寫法:

<html>
<head>
    <meta charset="utf-8">
    <style>
        #loading {
            position: absolute;
            top:0;
            left:0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,.2);
            display: none;
        }
        #loading span {
            position: absolute;
            top: 48%;
            left: 48%;
        }
    </style>
</head>
<body>
    <div id="loading"><span>loading...</span></div>
    <form id="demo">
        <input type="text" value="demo1" name="demo1">
        <input type="text" value="demo2" name="demo2">
        <input type="text" value="demo3" name="demo3">
        <input type="submit" value="提交" id="submit">
    </form>
</body>
</html>
<script>
    $(function(){
        $("#submit").click(function(){
        //  var data = $("form").serializeArray();
            var data = $("form").serialize();
            $.ajax({
                type:"get",
                url:"1.php",
                data:data,
                dataType:"json",
                success:function(data){
                    console.log(data);
                },
                error:function(xhr,error){
                    console.log(error);
                }
            })
        })
        // 1.9 以前寫法
        $("#loading").ajaxStart(function(){
            $(this).show();
        }).ajaxStop(function(){
            $(this).hide();
        })
        // 1.9+ 之后寫法
        $(document).ajaxStart(function(){
            $("#loading").show();
        }).ajaxStop(function(){
            $("#loading").hide();
        })
// 以上兩種簡寫
// 1.9 以前
$("#loading").on("ajaxStart ajaxStop",function(){
$(this).toggle();
})
// 1.9+ 以后
        $(document).on("ajaxStart ajaxStop",function(){ $("#loading").toggle(); }) }) </script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM