简体   繁体   English

如何在使用“全选”运算符(即“ *”)和jquery时获得点击元素?

[英]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. 此代码标识click事件并获取人员单击的html标记 ,并显示元素的索引 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) . 问题在于,它首先返回clicked元素html标签(这是必需的) ,然后再返回其父元素(这不是必需的) I only want the clicked element, not the parent element. 我只想要clicked元素,而不是父元素。 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 . 因为您使用的是*选择器,所以当您单击某个元素时,它会传播并触发每个祖先的click处理程序,直到到达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 ): 您可以只使用evt.stopPropagation() ,但是没有必要,因为您想要的东西已经可以通过evt.target (即,触发单击处理程序绑定到body的元素):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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