我有一个很大的区域需要使其可点击。假设我有一个项目列表:
<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()
*(由于模态,不是此特定问题的选项)*
- 这看起来像:
$("ul.my-area li").on('click',function (event) {
//location.href='SOME_LOCATION';
});
$("ul.my-area li a").on('click',function(e){
e.stopPropagation();
});
第二个解决方案:由于您已在 anchor
内嵌套了DIV、IMG...
,因此这里检查是否单击元素
不是 anchor
,或者如果它没有任何祖先 anchor
,并且在内部您可以更改location.href/do一些操作
:
$("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>
关于javascript - 只要不是 <a> 标签,就可以在单击某个区域时使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36204275/