当使用live()时,有没有一种方法可以强制事件只在给定的元素上激发一次(每个元素,而不是整个文档)

is there a way to force event to fire only once on given element (per element, not whole document) when using live()?

本文关键字:元素 文档 一次 事件 有没有 live 一种 方法      更新时间:2023-09-26
$('div.myclass').live('click',function() {
    alert('i should respond only once');
});

我知道jquery有一个one()函数,但我不知道如何将其与上面的代码集成。

$('div.myclass').live('click',function() {
   if($(this).attr('clicked') != 'yes')
   {
    alert('i should respond only once');
    $(this).attr('clicked', 'yes');
   }
});

live()单击处理程序中,您可以直接在调用e.stopPropagation()的元素上bind()事件。因此,在下一次单击时,事件将无法冒泡到文档中,因为它实际上会触发实时事件。

演示:http://jsfiddle.net/kKHJm/

$('li').live('click',function(){
    $(this).click(function(e){
        e.stopPropagation();
    });
    // Do stuff once here
});