簡體   English   中英

使用DOMSubtreeModified變異事件。 在jQuery中

[英]Using DOMSubtreeModified mutation event. in jQuery

我在我的頁面上使用了以下jQuery代碼,並且chrome上的一切正常。但是當我在firefox中打開相應的頁面時,我得到了無響應的腳本錯誤。

我知道根據DOM3規范,變異事件已被棄用。 但是,如果有人能幫助我在這里,我將被迫。

jQuery('#term').on("DOMSubtreeModified",function(){
$("#term > .click-slide").click(function(){
            $(this).siblings().slideToggle();

            });
 });

各自的HTML是:

<div class="btn-slide" id="term">
    <div class="click-slide">
      <button>Search Terms </button>
    </div>
    <div class="btn-box">
       <label><span>Novena</span></label>
    </div>
</div>

那么這可能不是一個合適的答案,因為問題是關於Mutation-events ,下面發布的是使用MutationObserver,但我仍然發布它,因為有些人可能覺得這很有用。

如果在DOM中添加了一些節點,這是我用於DOMSubtreeModified事件的替代方法。

var target = $( "#term" )[0];
// Create an observer instance
var observer = new MutationObserver(function( mutations ) {
   mutations.forEach(function( mutation ) {
       var newNodes = mutation.addedNodes; // DOM NodeList
       if( newNodes !== null ) { // If there are new nodes added

        //alert('something has been changed');

      }
   });    
});

// Configuration of the observer:
var config = { 
    attributes: true, 
    childList: true, 
    characterData: true 
};

// Pass in the target node, as well as the observer options
observer.observe(target, config);
// Later, you can stop observing
// observer.disconnect();

看起來在Firefox中,對.slideToggle()的調用會觸發DOMSubtreeModified事件,而Chrome中則不會發生這種情況。 所以基本上在Firefox中,某些東西最初會觸發綁定點擊處理程序的事件。 在這一點上一切都很好。 然后,當您繼續單擊時, slideToggle按預期發生。 然而,這會觸發DOMSubtreeModified事件,然后你最終會有兩個click事件處理程序都執行slideToggle因為它們現在已經注冊了兩次。 下次單擊時是無限循環發生的時間。 基本上,多次單擊事件會一直觸發DOMSubtreeModified ,它會注冊更多的點擊處理程序,這會使更多的slideToggles發生,從而觸發更多的DOMSubtreeModified ,依此類推。 要解決這個問題,你可以使用jQuery的.one ,告訴你的頁面只觸發一次DOMSubtreeModified處理程序,這會阻止這個循環。 如果這不是一個合適的解決方案,你只需要提出一些其他的方法來確保.click處理程序不會被綁定多次。

jQuery('#term').one("DOMSubtreeModified",function(){   //Notice this is using .one and not .on

看看這個JSFiddle - 它正在使用.one但是我能夠驗證在使用.on時,問題發生在Firefox而不是Chrome。

暫無
暫無

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

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