Is jQuery e.target suitable for best practice?

In my heavy ajax code, I always attach a “click” body tag and act on $(e.target)and using $.fn.hasClass(). However, when I click on the anchor with the tag </span>inside, mine $(e.target)is equal to this node, and not the parent anchor, as I would like.

From now on, I 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);
}

Something seems to be wrong ... Do you have a better implementation?


$.fn.live()does not solve my problem as it still returns span as the target. Also, I am looking for speed (works on atom-based touch devices), and life seemed slower (twice): http://jsperf.com/bind-vs-click/3


, @Guffa, $.fn.live() span, event.target. , "" ( bind ).

+3
3

live, ?

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

live body .

jQuery: live

+2

closest ( – live delegate — )

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

$t , — "a" .

:

HTML:

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

JavaScript jQuery:

jQuery(function($) {

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

});​

, , em - .

, jQuery live ( , , , , , ) delegate ( , live, ).

+2

, , bind , AJAX. live, jQuery .

0

Source: https://habr.com/ru/post/1781481/


All Articles