开发者

jQuery & livequery - check if a function has been attached to a element

I'm running this:

$("*:not(#boo) .content").livequery(function(){  
  $("input开发者_StackOverflow中文版, select").blah();
});

blah() looks like this:

(function( $ ) {
  $.fn.blah = function(){
    var that = this;
    return this.each(function(){
       $(this).bind('change', function(){
           // do some stuff here

           return true;
        }).change();

   });
 };

})(jQuery);

and the html looks like:

<div id="boo">
 <div class="content">
  <input type="text" />
  <input type="text" />
  ...
 </div>
</div>

<div class="content">    
 <input type="text" />
 <input type="text" />
</div>
...

so what I'm trying to do is to attach that function & event to every input element that is not inside #boo. This works, but the problem is that is doing it like every second over and over again and the browser freezes.

I need livequery because the html gets updated sometimes, and I need to attach the event again to new elements.

So how can I check if blah() has already been applied to a input element and stop there ?


I wouldn't do it that way to be honest. Your first statement is a big NoNo, by querying for every single node in your markup and THEN exluding the elements you need. Why not doing it like this:

$('input').filter(function() { return !!$(this).closest('#boo').length } )
          .live('change', function() {
              // do some stuff here
          }).change();

This of course only makes sense, if there isn't anything more to do which is out of my scope here. But it really looks like you don't even need the .livequery here.

Update

The above code couldn't work. But this should do it:

$('input').live('change', function() {
    if(!$(this).closest('#boo').length) {
        // do some stuff here
    }
}).change();


When you query $.data( object, 'events' ) you get an object back with properties of the events attached to it. So in your case you could add this conditional:

(function( $ ) {
  $.fn.blah = function(){
    var that = this;
    return this.each(function(){
       if ($.data( $(this).get(0), 'events' ) !== void(0) &&
           $.data( $(this).get(0), 'events' ).change === void(0)) {
           $(this).bind('change', function(){
               // do some stuff here
               return true;
           }).change();
       }
   });
 };
})(jQuery);

...in order to only bind the function if it hasn't been already.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜