Javascript 事件监听器刷新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17452924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:24:18  来源:igfitidea点击:

Javascript event listener refresh

javascriptjqueryhtmlcss

提问by Michael Guantonio

I have some javascript that I inherited for my job. In this javascript we have a side bar that is constantly updated(every 1 - 10 or so minutes). In the script we parse and process the AJAX from the server and then we call an interesting function.

我有一些 javascript 是我为我的工作继承的。在这个 javascript 中,我们有一个不断更新的侧栏(每 1 - 10 分钟左右)。在脚本中,我们解析和处理来自服务器的 AJAX,然后调用一个有趣的函数。

function renewClicks(){
    $('.classElem').unbind('click'); 
    $('.classElem2').unbind('click');
    $('.classElem3').unbind('click'); 

    $('.classElem').click(elm1funct); 
    $('.classElem2').clikc(elm2funct);
    $('.classElem3').click(elm3funct);  
}

Where .classElem is a css class selector that is appended to each image that is added to the page. And elmfunct is a function that is written to handle the click. This runs on each update (deauthorizing valid already added elements and then re adding them all). I want to know if there is a way I can possibly attach a listener on the body element in the DOM so that all of the image elements added to the page and that inherit the css class will already be handled and therefore not unregistered and re-registered on each update.

其中 .classElem 是一个 css 类选择器,它附加到添加到页面的每个图像。而 elmfunct 是一个用来处理点击的函数。这在每次更新时运行(取消授权已添加的有效元素,然后重新添加所有元素)。我想知道是否有一种方法可以在 DOM 中的 body 元素上附加一个侦听器,以便所有添加到页面并继承 css 类的图像元素都已经被处理,因此不会被取消注册和重新 -在每次更新时注册。

Thank you for any info you can provide.

感谢您提供的任何信息。

回答by DarkAjax

You could try this:

你可以试试这个:

$('body').on('click','.classElem',elm1funct)
         .on('click','.classElem2',elm2funct)
         .on('click','.classElem3', elm3funct);

From jQuery's docs:

来自jQuery 的文档

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

委托事件的优点是它们可以处理来自稍后添加到文档的后代元素的事件。通过选择在附加委托事件处理程序时保证存在的元素,您可以使用委托事件来避免频繁附加和删除事件处理程序的需要。

回答by Johan

As @crush mentioned, use an event delegated approach to avoid unbinding and re-binding events:

正如@crush 提到的,使用事件委托方法来避免取消绑定和重新绑定事件:

$(document).on('click', '.classElem', elm1funct);