jQuery - 只在页面上的每个元素触发一次直播事件?

时间:2011-10-27 20:13:47

标签: events jquery

以下是方案

$("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

  1. 简而言之,新的tumblr帖子正在无限滚动 javascript hack(tumblr fyi中唯一的那个。)
  2. inview插件会侦听要进入视口的新帖子,如果显示图像的顶部,则会使其可见。
  3. 它有点工作,但如果你在http://.syndex.me检查你的控制台,检查事件发生的频率
  4. 也许我也要挑剔,这没关系?请让我知道你的专业意见。但理想情况下,我希望停止做一些我不再需要的事情。
  5. 我试过的一些不起作用的东西:

    1. stopPropagation

    2. .die();

    3. 通过S.O.的一些解决方案。没有工作,例如In jQuery, is there any way to only bind a click once?Using .one() with .live() jQuery

    4. 我很惊讶为什么这样的选择还没有出现。当然,未来的元素也需要.one()事件吗? #justsayin

      感谢。

3 个答案:

答案 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")
   }
});

我使用了您网站上的实际代码。希望没关系。

相关问题