jquery - 不是防止触发父事件的选择器

标签 jquery html

我有以下 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()

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 falsestopPropagation() + 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/

相关文章:

javascript - Y 位置 javascript 上的 "Picking up" header

javascript - 试图了解 rerenderpin 函数在做什么?

javascript - Bootstrap Navbar(附加导航栏)在滚动期间调整大小

javascript - 使用Javascript函数将td的onclick设置为null

html - 等距圆圈,文本之间有线条,圆圈下方居中文本

javascript - 单击图像时jQuery shuffle div

javascript - JQuery animate 完整功能未运行

html - 为什么小空间不断出现在我的网页中?

html - float Div 的调整大小问题

html - IE中div高度和宽度的问题