jQuery 在单击内联 href 时防止 div 的单击行为

发布于 2024-12-15 16:58:39 字数 585 浏览 6 评论 0原文

我有一个包含 href 的 div。 div 有一个 jQuery 实时点击事件:

$(".item").live("click", function() { 
    window.location = this.id;  
});

在 div 中我有一个 href:

<div class="item" id="/test.html">
    <a href="javascript:void(0);" class="test" id="123">link</a>
</div>

还有一个实时点击事件:

$(".test").live("click", function() { 
    $(".item").unbind('click');
    alert(this.id);
});

我尝试实现的是单击 div 加载 div id 作为位置,同时单击 div 内的链接执行它自己的操作同时防止div点击行为。

我知道我可以从 div 中取出 href 但我不想要那个;-)

I have a div containing a href. The div has a jQuery live click event:

$(".item").live("click", function() { 
    window.location = this.id;  
});

In the div I have a href:

<div class="item" id="/test.html">
    <a href="javascript:void(0);" class="test" id="123">link</a>
</div>

Also with a live click event:

$(".test").live("click", function() { 
    $(".item").unbind('click');
    alert(this.id);
});

What I try to achieve is click the div loads the div id as location while clicking the link inside the div does it's own thing while preventing the div click behavior.

I know I could take the href out of the div but I don's want that ;-)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清醇 2024-12-22 16:58:39

更新

如果可以的话,请使用 jQuery 1.7 使用 .on 进行事件委托并阻止锚点点击传播:

$(document).on("click","a.test", function(e) { 
    e.stopImmediatePropagation();
});

$(document).on("click","div.item", function(e) { 
    // whatever
});

http://jsfiddle.net/AuHjA/3/

否则使用 .delegate 而不是 .live :

$(document).delegate("a.test", "click", function(e) { 
    e.stopPropagation();
});

$(document).delegate("div.item", "click", function(e) { 
    //whatever
});

http://jsfiddle.net/mblase75/AuHjA/4/

UPDATED

If you can, use jQuery 1.7 to do the event delegation using .on and stop the anchor clicks from propagating:

$(document).on("click","a.test", function(e) { 
    e.stopImmediatePropagation();
});

$(document).on("click","div.item", function(e) { 
    // whatever
});

http://jsfiddle.net/AuHjA/3/

Otherwise use .delegate instead of .live:

$(document).delegate("a.test", "click", function(e) { 
    e.stopPropagation();
});

$(document).delegate("div.item", "click", function(e) { 
    //whatever
});

http://jsfiddle.net/mblase75/AuHjA/4/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文