我曾使用live()
函数:
$('a.remove_item').live('click',function(e) {});
我需要将这个代码更改为one()
以防止多次点击,但是当我在页面加载后注入其中一个元素时,one()
监听器不会触发。
如何让one()
的行为像live()
?
我曾使用live()
函数:
$('a.remove_item').live('click',function(e) {});
我需要将这个代码更改为one()
以防止多次点击,但是当我在页面加载后注入其中一个元素时,one()
监听器不会触发。
如何让one()
的行为像live()
?
这是一个插件版本,用于运行一次.live()
处理程序,纯粹出于无聊而创建:
$.fn.liveAndLetDie = function(event, callback) {
var sel = this.selector;
function unbind() { $(sel).die(event, callback).die(event, unbind); }
return this.live(event, callback).live(event, unbind);
};
它的工作方式就像.live()
一样(除非您需要事件数据参数,在这种情况下,您需要添加重载)。只需以相同的方式使用它:
$('a.remove_item').liveAndLetDie('click', function(e) { /* do stuff */ });
$('.class')
),它只会在选择器中的任何一个元素上运行一次(即如果第一个元素被点击,则第二个元素无法被点击),而在第一个答案中,每个元素只能被点击一次(即你可以先点击第一个元素一次,然后点击第二个元素一次,以此类推)。因此,在我的情况下,与这个答案相比,我发现被标记为正确的答案更有益。我没有建议任何编辑,只是指出了一个差异。 - Lucas尝试这样做:
$('a.remove_item').live('click',function(e) {
if($(e.target).data('oneclicked')!='yes')
{
//Your code
}
$(e.target).data('oneclicked','yes');
});
这会执行你的代码,但它还会设置一个名为'oneclicked'的标志为yes,以便它不会再次激活。基本上只是设置一个停止激活的设置,一旦被点击一次就会停止。
$('a.remove_item')
,那将是很好的。 - Blowsie在处理程序中使用 jQuery 的 .die()
方法 :
例子: http://jsfiddle.net/Agzar/
$('a.remove_item').live('click',function(e) {
alert('clicked');
$('a.remove_item').die('click'); // This removes the .live() functionality
});
编辑:
或者,如果您只想在每个元素上禁用事件,您可以更改类名,因为live()
是基于选择器的。
示例:http://jsfiddle.net/Agzar/1/
$('a.remove_item').live('click',function(e) {
alert('i was clicked');
$(this).toggleClass('remove_item remove_item_clicked');
});
这将类从remove_item
更改为remove_item_clicked
,这两个类可能具有相同的样式。现在,live()
将不会在第一次点击后触发。
试试这个
$('a.remove_item').live('click', function(e) {
if(!$(this).hasClass('clicked'))
{
$(this).addClass('clicked');
alert("dd"); // this is clicked once, do something here
}
});
我知道这是一个旧帖子,但是在类似的情况下,这对我有用:
$('a.remove_item').live('click', function(e) {
e.stopPropagation();
// Your code here
});
我在$.ajax函数中使用它,所以最后,在我的情况下失败,我使用500来延迟它并停止多次重发。
}).fail(function(response, status){
alert("FAILED: "+JSON.stringify(response, null, 4));
},500);
希望对你有所帮助!