觸發的 jQuery 事件的順序是什麼?


jQuery 事件處理程式始終按照它們被繫結的順序執行。使用 jQuery,你還可以更改順序。讓我們來看看比如從

demo(1);
demo(2);

我們可以將順序更改為 -

demo(2);
demo(1);

示例

你可以嘗試執行以下內容來學習並更改 jQuery 事件的順序 -

實際演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $.fn.bindFirst = function(name, fn) {

        this.on(name, fn);
        this.each(function() {
            var handlers = $._data(this, 'events')[name.split('.')[0]];
            var handler = handlers.pop();
            handlers.splice(0, 0, handler);
        });
    };

    $("div").click(function() { alert("1"); });
    $("div").click(function() { alert("2"); });
    $("div").click(function() { alert("3"); });
    $("div").click(function() { alert("4"); });  
    $("div").bindFirst('click', function() { alert("5"); });

});
</script>
</head>
<style>    
.demo {
    cursor: pointer;
    border: 3px solid #FF0000;    
}
</style>
<body>

<h1>Heading 1</h1>
<div class="demo">
Click here for sequence.<br>
The sequence will be: 5, 1, 2, 3, 4
</div>

</body>
</html>

更新於: 2020-2-14

832 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告