我有以下 html 代码
<div class="overlay" data-url="http://www.example1.org">
Lorem ipsum dolor sit amet, consectetur adipisicing elit
<a class="link1 clickThis" href="http://www.example2.org">
first link
</a>
<a class="link2 clickThis" href="http://www.example3.org">
Second link
</a>`
</div>
我无法直接链接到覆盖 div,我想在单击 div 和链接后重定向到受尊重的 url,当用户单击链接时,它应该重定向到特定的 url。 但是如果用户点击 a 的外侧,那么它应该重定向到设置为 data-url 属性的 url。
这样我就编写了这个 JQuery 代码
$('.overlay').click(function(event) {
event.preventDefault();
window.location.href = $(this).attr('data-url');
}).children('a').click(function(event) {
return false;
});
// methods call on link click
$(document).on('click', '.clickThis', function(event) {
event.preventDefault();
$.ajax({
url: $(this).attr('href'),
type: 'GET',
data: {
param1: 'value1'
},
})
.done(function() {
console.log("success");
})
});
但是点击链接后这不起作用
也尝试过这个
$('.overlay:not(.link1,.link2)').click(function(event) {
event.preventDefault();
window.location.href = $(this).attr('data-url');
});
请指定正确答案。 谢谢。
最佳答案
您需要stopPropagation()在 anchor 上。您当前正在使用 return false
这可以防止 anchor 发生默认行为。通过停止在 anchor 上的传播,可以防止事件向上冒泡到祖先元素。
event.stopPropagation()
block 引用>Returns: Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
$('.overlay').click(function(event) { window.location.href = $(this).attr('data-url'); }).children('a').click(function(event) { event.stopPropagation(); });
由于您使用ajax作为 anchor ,您可以使用
return false
或stopPropagation() + preventDefault()
$('.overlay').click(function(event) { event.preventDefault(); window.location.href = $(this).attr('data-url'); }).children('a').click(function(event) { $.ajax({ url: $(this).attr('href'), type: 'GET', data: { param1: 'value1' }, }).done(function() { console.log("success"); }) return false; });
关于jquery - 不是防止触发父事件的选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32332053/