Javascript事件监听器刷新 [英] Javascript event listener refresh

查看:138
本文介绍了Javascript事件监听器刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些我为我的工作继承的javascript。在这个JavaScript中,我们有一个不断更新的边栏(每隔1到10分钟)。在脚本中,我们解析并处理来自服务器的AJAX,然后调用一个有趣的函数。
$ b

 函数renewClicks(){
$('。classElem')。unbind('click');
$('。classElem2')。unbind('click');
$('。classElem3')。unbind('click');

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

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



感谢您提供任何信息。

解决方案

您可以试试这个:

 <$ ('click','。classElem',elm1funct)
.on('click','。classElem2',elm2funct)
.on('点击','。classElem3',elm3funct);

From jQuery的文档

lockquote

委托事件的优点是可以处理事件来自
后来添加到文档中的后代元素。通过
挑选一个保证在
委托事件处理程序附加时存在的元素,可以将委派事件用于
,从而避免需要经常附加和删除事件处理程序。 / p>


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.

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.

Thank you for any info you can provide.

解决方案

You could try this:

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

From jQuery's docs:

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.

这篇关于Javascript事件监听器刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆