jQuery.live() not working inside of a plugin

邮差的信 提交于 2019-12-22 09:26:30

问题


I am writing a plugin and need to live bind a click. The plugin works fine when I do a normal click bind, but not a live bind.

I've boiled the plugin down to the basics:

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

When I call the plugin function on a link, only click is printed to my console.

What must I do in order for live() to work? Thanks.


回答1:


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();



回答2:


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.




回答3:


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(); });



回答4:


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);



回答5:


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?



来源:https://stackoverflow.com/questions/2300081/jquery-live-not-working-inside-of-a-plugin

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