简体   繁体   English

当事件设置为外部元素时,如何检测另一个元素内的元素?

[英]How can I detect the element inside another element while the event is set to the outer one?

Here is my code: 这是我的代码:

 $("div").on('click', function(e){ e.preventDefault(e); /* if ( clicked element is <a> element ){ redirect to the href and return false } */ alert("div clicked"); }) 
 div{ cursor: pointer; border: 1px solid; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <p>this is a paragraph</p> <a href="/url">this is a link</a> <p>this is another paragraph</p> </div> 

How can I make that condition (which is commented in code above) working? 如何使该条件(在上面的代码中注释)有效? I need to detect if the clicked element inside <div> is a <a> , then redirect to it and die. 我需要检测<div>被点击元素是否是<a> ,然后重定向到它并死掉。 How can I do that? 我怎样才能做到这一点?

You can use e.target to get the clicked element. 您可以使用e.target获取单击的元素。 To check what tag is clicked, you can use e.target.tagName 要检查单击的标记,可以使用e.target.tagName

 $("div").on('click', function(e) { e.preventDefault(e); if ( e.target.tagName === 'A' ) { var href = $(e.target).attr('href'); console.log(href); } //e.target.tagName - Will return 'A' if <a> is clicked. }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <p>this is a paragraph</p> <a href="/url">this is a link</a> <p>this is another paragraph</p> </div> 

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

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