我如何确定这个被点击的元素是否是某些菜单的子集?
jQuery示例:
var clicked = e.target;
// this checks see if the clicked has id of somemenu.
$(clicked).attr("id") == '#somemenu';somemenu的HTML示例:
<div id="somemenu">
<a href="something.php"> menu 1 </a>
<!--bunch of other elements here, can be anything.-->
</div>我想捕捉任何属于`div#somemenu的子集的元素。当它被点击。
发布于 2010-09-25 10:01:33
这将会起作用:
if ($(clicked).parents('#somemenu').length) {
// I am a child of somemenu so do stuff.
} 发布于 2017-05-03 22:59:49
使用stopPropagation和jquery的on方法会更容易:
jQuery('#myID').on('click',"*",function(e){
e.stopPropagation(); //stop the propagation
console.log("Clicked element: ",jQuery(this)); //get the element clicked by the mouse
console.log("Parent: ",jQuery(this).closest("#myID"));
});如果您不停止传播,您应该调用jQuery(this);的所有父级
发布于 2016-08-02 21:20:26
一个更干净、更具可读性的解决方案
if($.contains(someElement, clicked)){ // DO STUFF }https://stackoverflow.com/questions/3792122
复制相似问题