簡體   English   中英

處理多個文檔就緒事件偵聽器

[英]Handling multiple document ready event listeners

我的代碼中有多個文檔就緒事件監聽器。

$(document).ready(function() {
  console.log("hello james")
});

$(document).ready(function() {
  console.log("hello cindy")
});


$(document).ready(function() {
  console.log("hello dave")
});

我只希望在用戶訪問頁面時准備好調用第一個文檔。 我不需要其他兩個文檔准備調用。

我不能使用全局變量來檢查這一點。 我希望做的是使用bind 我的理論是通過將代碼設置為...

$(document).bind("ready", function() {
  console.log("hello james")
});

$(document).bind("ready", function() {
  console.log("hello cindy")
});


$(document).bind("ready", function() {
  console.log("hello dave")
});

只有第一個綁定會調用。 這就是我目前對bind如何工作的理解。

現在,這里是踢腿者。 我需要做的是,一旦這些綁定運行(再次,我只希望第一個綁定被執行,從而在控制台日志中打印出“ hello james”),我就需要取消准備就緒的文檔的綁定。 我在想做...

$(document).bind("ready", function() {
  console.log("hello james")
  $(document).unbind("ready");
});

$(document).bind("ready", function() {
  console.log("hello cindy")
});


$(document).bind("ready", function() {
  console.log("hello dave")
});

但這不起作用。 “ hello james”將被記錄,但ready事件不會解除綁定。 我在這里想念什么嗎? 我究竟做錯了什么?

您可以嘗試event.stopImmediatePropagation()
這可以防止執行綁定到同一事件的任何其他處理程序:

 $(document).on("ready",function(e) { e.stopImmediatePropagation(); console.log("hello james"); }); $(document).on("ready",function(){console.log("hello cindy");}); $(document).on("ready",function(){console.log("hello dave");}); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
jsfiddle: https ://jsfiddle.net/L6j23hao/2/

(我將.ready(更改為.on("ready",因為否則代碼段和jsfiddle都將無法工作/不會產生錯誤,盡管我不明白為什么。據我所知, .ready(應該可以正好。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM