只要区域不是<a>标签

React on click over an area as long as it was not an <a> tag

本文关键字:gt 标签 lt 区域      更新时间:2023-09-26

我有一个很大的区域需要使其可点击。想象一下,我有一个项目列表:

<ul class="my-area">
    <li>...</li>
    <li>...</li>
</ul>

项目<li>里面有很多东西,包括工作链接或触发模式窗口的链接等。只要有人点击其中一个链接,它就应该执行指定的操作-重定向、打开模式窗口等。然而,如果点击的不是链接,而是<div><span>等,那么我需要重定向到特定位置。

我试过这个:

$("ul.my-area li:not(a)").click(function (event) {
    location.href='SOME_LOCATION';
});

然而,它不起作用。我也考虑过使用.stopPropagation(),但后来模式窗口停止工作,所以这不是一个选项。有什么想法吗?

编辑:有两种可能的解决方案:

第一种解决方案:event.stopPropagation()*(not an option for this specific question because of modals)*-看起来像:

$("ul.my-area li").on('click',function (event) {           
//location.href='SOME_LOCATION';
});
$("ul.my-area li a").on('click',function(e){
  e.stopPropagation();
}); 

第二个解决方案:由于您在anchors中嵌套了DIV, IMG...,因此在这里它将检查clicked element是否不是anchor或是否没有任何ancestor anchor,并且在内部您可以更改location.href/do some action

$("ul.my-area li ").on('click', function(event) {
      if (!((event.target.tagName == "A") || $(event.target).closest('a').length)) {
        console.log("This is not an anchor");
        //location.href='SOME_LOCATION';
      }
      else{ //it's an anchor }
    });


查看下面的片段

$("ul.my-area li ").on('click', function(event) {
  if (!((event.target.tagName == "A") || $(event.target).closest('a').length)) {
    console.log("This is not an anchor");
    //location.href='SOME_LOCATION';
  }
  else{ //it's an anchor }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="my-area">
  <li>
    <p>This is Paragraf <a href="#">This is Anchor</a>
    </p>
    <div>This is DIV</div>
  </li>
  <li>
    <p>This is another Paragraf</p>
    <a href="#">
      <div>This Div inside Anchor<span> This is span inside div inside the anchor</span>
      </div>
      <img src="" alt="Image part of the anchor">
    </a>
    <p>Some paragraf</p>
  </li>
</ul>