jQuery.live() not working inside of a plugin

半世苍凉 提交于 2019-12-05 20:25:58

this works without workarounds outside of the plugin:

(function ($) {
    $.fn.liveBindTest = function () {
        return this['live']('click', function () {
            console.log('click');
            return false;
        });
    };
})(jQuery);

$('a').liveBindTest();

Any particular reason you have 2 click event binded into a single object? The second bind will overwrite the live bind, so the live will never fired.

After thinking this through, I realized it makes no sense to call live on an existing DOM element because it's already in the DOM.

Trick is to use live when invoking the plugin:

(function($) {
  $.fn.liveBindTest = function() {
    return this.each(function() {
      $(this).click(function(){
        console.log('click');
        return false;
      });
    });
  };
})(jQuery);
$('a').live('click', function(){ $(this).liveBindTest(); });

I find this works (jQuery 1.5.2):

(function($) {
$.fn.clickTest = function () {
    return this.each(function() {
        $('.clicker').die('click').live('click', function() {
            console.log('clicked');
        });
        $(this).click(function() {
            $('body').append('<a href="#" class="clicker">click here '+$(this).attr('id')+'</a><br> ');

        });
    });
}; }) (jQuery);

I think it's not a good point of view. Now suppose that your plugin is a sort of lightbox,and it is looking to anchor elements inside the DOM. Usually at the dom ready you will do something like

$(dom_elements).myplugin();

What if your appending some links via jsor ajax to your page? I don't think that rebinding using your

$('a').live('click', function(){ $(this).liveBindTest(); });

is going to be the right way!It will work but telling the truth i don't think that it will be a "best practice". The real problem is that with jQuery 1.4.2 the live event delegation is waiting for a string('a.test') and not for an object(this).Could it be a jQuery 1.4.2 bug?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!