使用DomSubtree修改了突变事件。在jQuery中
我在我的页面上使用了以下jQuery代码,在chrome上一切正常。但是当我在firefox中打开相应的页面时,我得到了无响应的脚本错误 我知道根据DOM3规范,突变事件已被弃用。但如果有人能帮我,我会很感激的使用DomSubtree修改了突变事件。在jQuery中,jquery,html,firefox,mutation-events,Jquery,Html,Firefox,Mutation Events,我在我的页面上使用了以下jQuery代码,在chrome上一切正常。但是当我在firefox中打开相应的页面时,我得到了无响应的脚本错误 我知道根据DOM3规范,突变事件已被弃用。但如果有人能帮我,我会很感激的 jQuery('#term').on("DOMSubtreeModified",function(){ $("#term > .click-slide").click(function(){ $(this).siblings().slideToggle();
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>
搜索词
诺维纳
在Firefox中,调用.slideToggle()
会触发domsubtreemedited
事件,而在Chrome中不会发生这种情况。因此,基本上在Firefox中,最初会触发绑定单击处理程序的事件。在这一点上,一切都是好的。然后继续单击时,slideToggle
按预期进行。但是,这会触发DOMSubtreeModified事件,然后您会得到两个click事件处理程序,它们都执行slideToggle
,因为它们现在已注册两次。下一次单击是无限循环发生时。基本上,多个单击事件会不断触发domsubtreedined
,这会注册更多的单击处理程序,从而发生更多的slideToggles
,从而触发更多的domsubtreedined
s,依此类推。要解决这个问题,您可以使用jQuery的.one
,它告诉页面只触发domsubtreemedited
处理程序一次,这就防止了这个循环。如果这不是一个合适的解决方案,您只需要想出一些其他方法来确保。单击处理程序不会绑定多次
jQuery('#term').one("DOMSubtreeModified",function(){ //Notice this is using .one and not .on
看看这个-它使用的是.one
,但我能够验证在使用.on时,问题发生在Firefox而不是Chrome上。这可能不是一个合适的答案,因为问题是关于变异事件的,下面的帖子使用了,但我仍然在发布它,因为有些人可能会觉得这很有用
这是我在DOM中添加某些节点时用于domsubtreemedition事件的替代方法
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();
这解释得很好。我注意到用“.on”代替小提琴中的“.one”时发生了什么。谢谢。哇。。。你回答了我的问题和我刚才的一个问题。我从未听说过。一个函数示例。使用一些jquery。谢谢非常感谢。是的,非常有帮助。谢谢!我修改为突变[0]。添加了节点
,以仅获得我病例中的第一个突变。再次感谢。