以下是方案
$("p").live('customEvent', function (event, chkSomething){
//this particular custom event works with live
if(chkSomething){
doStuff();
// BUT only per element
// So almost like a .one(), but on an elemental basis, and .live()?
}
})
以下是一些背景
自定义事件来自plugin called inview
实际问题在这里http://syndex.me
我试过的一些不起作用的东西:
stopPropagation
.die();
通过S.O.的一些解决方案。没有工作,例如In jQuery, is there any way to only bind a click once?或Using .one() with .live() jQuery
我很惊讶为什么这样的选择还没有出现。当然,未来的元素也需要.one()事件吗? #justsayin
感谢。
答案 0 :(得分:2)
在事件发生时向元素添加一个类,并且只在没有该类的元素上发生事件。
$("p:not(.nolive)").live(event,function(){
$(this).addClass("nolive");
dostuff();
});
编辑:评论示例:
$("p").live(event,function(){
var $this = $(this);
if ($this.data("live")) {
return;
}
$this.data("live",true);
doStuff();
});
答案 1 :(得分:1)
这个有效(见fiddle):
jQuery(function($) {
$("p").live('customEvent', function(event, chkSomething) {
//this particular custom event works with live
if (chkSomething) {
doStuff();
// BUT only per element
// So almost like a .one(), but on an elemental basis, and .live()?
$(this).bind('customEvent', false);
}
});
function doStuff() {
window.alert('ran dostuff');
};
$('#content').append('<p>Here is a test</p>');
$('p').trigger('customEvent', {one: true});
$('p').trigger('customEvent', {one: true});
$('p').trigger('customEvent', {one: true});
});
这也应该可以满足您的需求,虽然它不是很漂亮:)
$("p").live('customEvent', function (event, chkSomething){
//this particular custom event works with live
if(chkSomething && $(this).data('customEventRanAlready') != 1){
doStuff();
// BUT only per element
// So almost like a .one(), but on an elemental basis, and .live()?
$(this).data('customEventRanAlready', 1);
}
})
答案 2 :(得分:1)
凯文提到,你可以通过操纵CSS选择器来实现这一点,但实际上你不必使用:not()
。这是另一种方法:
// Use an attribute selector like so. This will only select elements
// that have 'theImage' as their ONLY class. Adding another class to them
// will effectively disable the repeating calls from live()
$('div[class=theImage]').live('inview',function(event, visible, visiblePartX, visiblePartY) {
if (visiblePartY=="top") {
$(this).animate({ opacity: 1 });
$(this).addClass('nolive');
console.log("look just how many times this is firing")
}
});
我使用了您网站上的实际代码。希望没关系。