html div onclick event(html div onclick 事件)
问题描述
我的jsp页面上有一个html div,我在上面放了一个锚标签,请在下面找到代码,
I have one html div on my jsp page, on that i have put one anchor tag, please find code below for that,
<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
方法.
here I when I click on div I got alert with 123
message, its fine but when I click on ABC I want message I want to call markActiveLink
method.
JSFiddle
我的代码有什么问题?请帮帮我.
what is wrong with my code? please help me out.
推荐答案
问题是点击锚点仍然触发了你的 <div>
中的点击.这就是所谓的事件冒泡".
The problem was that clicking the anchor still triggered a click in your <div>
. That's called "event bubbling".
其实有多种解决方案:
在 DIV 点击事件处理程序中检查实际的目标元素是否是锚点
→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"));
});
从锚点点击监听器停止事件传播
→jsFiddle
$("#ancherComplaint").click(function (evt) {
evt.stopPropagation();
alert($(this).attr("id"));
});
您可能已经注意到,我从示例中删除了以下选择器部分:
As you may have noticed, I have removed the following selector part from my examples:
:not(#ancherComplaint)
这是不必要的,因为没有类 .expandable-panel-heading
的元素也有 #ancherComplaint
作为其 ID.
This was unnecessary because there is no element with the class .expandable-panel-heading
which also have #ancherComplaint
as its ID.
我假设您想抑制锚点的事件.这不能以这种方式工作,因为两个选择器(你的和我的)都选择完全相同的 DIV.选择器在被调用时对监听器没有影响;它仅设置侦听器应注册到的元素列表.由于此列表在两个版本中都是相同的,因此没有区别.
I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.
这篇关于html div onclick 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:html div onclick 事件


- addEventListener 在 IE 11 中不起作用 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01