我的 jsp 页面上有一个 html div,我在上面放了一个 anchor 标记,请在下面找到代码,
<div class="expandable-panel-heading">
<h2>
<a id="ancherComplaint" href="#addComplaint"
onclick="markActiveLink(this);">ABC</a>
</h2>
</div>
js代码
$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});
function markActiveLink(el) {
alert($(el).attr("id"));
}
在这里,当我点击 div 时,我收到了 123
消息的警报,这很好,但是当我点击 ABC 时,我想要消息 I想调用markActiveLink
方法。
我的代码有什么问题?请帮助我。
最佳答案
问题是点击 anchor 仍然会触发您的 <div>
中的点击.这叫做“event bubbling”。
其实有多种解决方案:
在 DIV 单击事件处理程序中检查实际目标元素是否为 anchor
→ jsFiddle$('.expandable-panel-heading').click(function (evt) { if (evt.target.tagName != "A") { alert('123'); } // Also possible if conditions: // - evt.target.id != "ancherComplaint" // - !$(evt.target).is("#ancherComplaint") }); $("#ancherComplaint").click(function () { alert($(this).attr("id")); });
停止从 anchor 击监听器传播事件
→ jsFiddle$("#ancherComplaint").click(function (evt) { evt.stopPropagation(); alert($(this).attr("id")); });
您可能已经注意到,我从示例中删除了以下选择器部分:
:not(#ancherComplaint)
这是不必要的,因为类 .expandable-panel-heading
中没有元素还有#ancherComplaint
作为它的 ID。
我假设您想抑制 anchor 的事件。这不能以那种方式工作,因为两个选择器(你的和我的)选择完全相同的 DIV。选择器在被调用时对监听器没有影响;它只设置监听器应该注册到的元素列表。由于此列表在两个版本中相同,因此不存在差异。
关于javascript - html div onclick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19655843/