简体   繁体   中英

Detecting click on inner div with event.target

I have an accordion that when it is clicked (the whole element) it triggers and displays the inner items. I want to be able to add an accordion inside of one of the inner items, so I'm using event.target to see where the click happens. For some reason, event.target detects the click on an inner paragraph, but not on it's wrapper div? What is the reason of this?

$(".gestion-accordion-wrap").on("click", function(event){

      var $target = $( event.target );

      if ( $target.is ( $(".gestion-inner-wrap p") ) ){

        var $innerWrap = $(".gestion-inner-wrap p").parent().parent();

        $innerWrap.children().eq(1).slideToggle(300); 
        $innerWrap.find(".mas-detalles-clickable-inner").toggleClass("clickable-spin");
        $innerWrap.find(".mas-detalles-after-inner").toggle();
        $innerWrap.find(".menos-detalles-after-inner").toggle();

        $innerWrap.find(".span-left-line").toggleClass("left-line-grow");

      } else {

  $(this).children().eq(1).slideToggle(300); 
  $(this).find(".mas-detalles-clickable").toggleClass("clickable-spin");
  $(this).find(".mas-detalles-after").toggle();
  $(this).find(".menos-detalles-after").toggle();
  $(this).find(".span-left-line").toggleClass("left-line-grow");
}})

Why is this detected:

if ( $target.is ( $(".gestion-inner-wrap p") ) ){

But not this?

if ( $target.is ( $(".gestion-inner-wrap") ) ){

( NOTE : There's no p in this selector)

This is the way DOM works ! .

target property is intended to match only that exact element on which a given event occurs , the handler which caught the event doesn't matter .What you need instead is currentTarget property.

currentTarget

Identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to event.target which identifies the element on which the event occurred.

$(".gestion-accordion-wrap").on("click",'*',  function(event){

  var $target = $( event.currentTarget );
  alert( $target.is ( $(".gestion-inner-wrap") ) ); // TRUE

}

https://jsfiddle.net/mbzp2xcp/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM