简体   繁体   English

$(e.target)等于一个链接,即使单击其中的元素?

[英]$(e.target) equals a link even if clicking on element within?

I feel I should be more experienced then this however I just cannot seem to resolve. 我觉得我应该对此更有经验,但是我似乎无法解决。 Upon clicking on the link or anything within, I want this to be the $(e.target) to call the parent or whatnot. 在单击链接或其中的任何内容后,我希望它成为调用父项或其他项的$(e.target)

A breakdown of my script looks like the following; 我的脚本细分如下所示;

$(document).on('mousedown', function(e) {
    if ($(e.target).is('ul.SiteNav>li>a')) {
    alert('Hello World!')
  }
});

Of course this is just a snippet but nevertheless, I'm new to using $(e.target) an despite my searches, I cannot resolve to as why you cannot click the <i></i> within the <a></a> because you're still clicking on the link, aren't you/... 当然,这只是一个片段,不过尽管如此,我还是使用$(e.target)一个新手,尽管我进行了搜索,但我无法解析为为什么您无法单击<a></a><i></i> <a></a>因为您仍在点击链接,不是吗?

Here is a JSFiddle example of my problem 这是我的问题的JSFiddle示例

target will be whatever deepest level element you actually interact with but what is likely confusing you is that events bubble up the dom tree so if an event handler was listening to <a> click, clicking on a child will still bubble to the parent and trigger the event handler target将是您实际与之交互的最深层元素,但可能会使您感到困惑的是,事件在dom树中冒泡,因此,如果事件处理程序正在监听<a>单击,则单击子级仍会冒泡到父级并触发事件处理程序

Use closest() to do what you want 使用closest()做你想要的

if ($(e.target).closest('.SiteNav a').length){
   // code if <a> expected
}else{
   // do something else when not <a>
 }

closest() will also include the actual target and work it's way up from that start point. closest()也将包括实际目标,并从该起点开始逐步进行。

You can click it, and you actually get the event. 您可以单击它,然后您实际得到该事件。 Only e.target is the element you clicked. 单击的元素只有e.target。 And it makes sense. 这是有道理的。 The handlers is on document, the element is the i .. why would the link get the click? 处理程序在文档上,元素是i ..为什么链接会获得点击?

You can try to find it in the parent chain using closest() . 您可以尝试使用closest()在父链中找到它。 It will give a result when the element itself or one of its parents match the given selector. 当元素本身或其父元素之一与给定的选择器匹配时,将给出结果。

 $(document).on('mousedown', function(e) { if ($(e.target).closest('ul.SiteNav>li>a').length > 0) { alert('Hello World!') } }); 
 .SiteNav { List-style:none; } a { float:left; height:42px; line-height:42px; padding:0 10px; color: #f7dd71; text-decoration: none; font-size: 14px; font-family: "Comic Sans MS", cursive, sans-serif; font-weight: bold; } a:nth-of-type(1) { padding-right:2px; } a:nth-of-type(2) { padding:0 5px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="SiteNav"> <li><a href="javascript:;" data-link="Reply">Reply</a></li> <li><a href="javascript:;" data-link="Reply"><i class="fa fa-angle-down"></i></a></li> </ul> 

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

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