使用DOMSubtreeModified变异事件。在jQuery中

问题描述 投票:9回答:2

我在我的页面上使用了以下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>
jquery html firefox mutation-events
2个回答
14
投票

看起来在Firefox中,对.slideToggle()的调用触发了DOMSubtreeModified事件,而这在Chrome中并没有发生。所以基本上在Firefox中,某些东西最初会触发绑定点击处理程序的事件。在这一点上一切都很好。然后,当您继续单击时,slideToggle按预期发生。然而,这会触发DOMSubtreeModified事件,然后您最终会有两个单击事件处理程序,它们都执行slideToggle,因为它们现在已经注册了两次。下次单击时是无限循环发生的时间。基本上,多次点击事件会继续触发DOMSubtreeModified,它会记录更多的点击处理程序,这会使更多的slideToggles发生,从而触发更多的DOMSubtreeModifieds,依此类推。要解决这个问题,你可以使用jQuery的.one来告诉你的页面只启动一次DOMSubtreeModified处理程序,这会阻止这个循环。如果这不是一个合适的解决方案,你只需要提出一些其他的方法来确保.click处理程序不会被绑定多次。

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

看看这个JSFiddle - 它正在使用.one但我能够验证在使用.on时,问题发生在Firefox而不是Chrome。


15
投票

那么这可能不是一个合适的答案,因为问题是关于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();
© www.soinside.com 2019 - 2024. All rights reserved.