开发者

jQuery e.target bubbling best practice?

开发者 https://www.devze.com 2023-01-31 20:55 出处:网络
In my heavy-ajax code, i always bind \"click\" the body tag & act depending on $(e.target) & using $.fn.hasClass(). However when i click on an anchor that has开发者_开发百科 a </span> ta

In my heavy-ajax code, i always bind "click" the body tag & act depending on $(e.target) & using $.fn.hasClass(). However when i click on an anchor that has开发者_开发百科 a </span> tag inside, my $(e.target) equals this node, and not the parent anchor as i would like it to.

From now on, i have used this trick (var $t = $(e.target);) :

/** bubbling **/
if($t.get(0).tagName !== "A" && $t.get(0).tagName !== "AREA") {
    $t = $t.parent("a");
   if(empty($t)) return true;
   //else console.log("$t.bubble()", $t);
}

It feels wrong somehow... Do you have any better implementation ?


$.fn.live() does not solve my issue as it still returns the span as the target. Moreover i'm looking for speed (running on atom-based touch devices) & live appeared to be way slower (twice) : http://jsperf.com/bind-vs-click/3


In fact, as @Guffa pointed, using $.fn.live() solves the span bubbling issue as i don't need the event.target anymore. I guess there is no other "right" answer here (using bind on a container).


Why not use the live method that does it for you?

$('a.someclass').live('click', function(){
  // do something
});

The live method binds to the body element and checks the event target against the selector.

jQuery: live


closest is useful here (though other methods — live and delegate — are described below):

$t = $t.closest('a');

That starts with $t and works upward through the chain of parent elements until it finds one matching the given selector — "a" in this case.

Here's a rudimentary example:

HTML:

<a href='#'><span>Outer span <span>inner span <em>em</em></span></span></a>

JavaScript using jQuery:

jQuery(function($) {

  $(document).click(function(e) {
    var $t = $(e.target).closest('a');
    $t.css("border", "1px solid black");
    return false;
  });

});​

Live copy

Clicking the link puts a border around the link, whether you click in one of the spans or the em element or wherever.

Somewhat off-topic, but recent versions of jQuery handle this for you via live (which basically does what you do, hooks an event on the body and then looks to see what actual element it happened on, applying a selector to element matching) and delegate (same as live but rooted in a specific element instead of the document itself).


I presume you're doing this because bind does not work on content inserted after an AJAX call. I would recommend you use live to attach your events and allow jQuery to handle this.

0

精彩评论

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