gpt4 book ai didi

javascript - 仅使用 "on"响应所需元素 :

转载 作者:行者123 更新时间:2023-11-30 10:12:41 25 4
gpt4 key购买 nike

JS Fiddle Link

我正在动态添加一些元素,我的 div 看起来像:

<div class="knock" href="#">  
<!-- Do Something if links are not clicked -->
<a href="http://google.com" target="_blank">Google</a>
<a href="http://facebook.com" target="_blank">Facebook</a>
</div>

我的 on 脚本是:

$(".knock").on("click", function(){
console.log("Link not clicked");
alert("Link not Clicked");

});

我的问题是,我不想在单击链接时触发警报。有出路吗?

最佳答案

您可以编写 anchor 标记事件并停止事件传播到上层 DOM 元素,以便仅在实际单击 div 时才会出现警报,而不是在单击 div 内的某些 anchor 标记时出现:

$(".knock").on('click',"a",function(event){

event.stopPropagation();

})

fiddle :

http://jsfiddle.net/hbac7vbh/2/

event.stopPropagation:

The event.stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed.

参见 details here on jquery official page

关于javascript - 仅使用 "on"响应所需元素 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25610778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com