简体   繁体   中英

how to get clicked element while using “select all” operator i.e “ * ” using jquery?

 $('body').on("click", "*", function(e) { console.log("clicked tag:" + this.tagName); console.log("index:(" + this.tagName + ")[" + $(this).index(this.tagName) + "]"); }); 
 <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <div> <p>hello !</p> <div> <p>stack overflow</p> </div> </div> </body> </html> 

This code identifies the click event and gets the html tag clicked by the person and also displays the index of the element. The problem is that it first returns the html tag of the clicked element(which is required) and then after that it also returns the parent element as well(which is not required) . I only want the clicked element, not the parent element. How am i supposed to do it?

Because you're using the * selector, when you click on an element, it's propagating and triggering the click handler for every ancestor on the way up to the body . You could just use evt.stopPropagation() , but there's no need because what you want is already available via evt.target (ie. the element that triggered the click handler bound to the body ):

$( 'body' ).on( 'click', function( evt ) {
  console.log( evt.target );
} );

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