执行重定向而不冒冒点击事件

时间:2013-11-05 16:34:27

标签: jquery html events event-bubbling jquery-click-event

我在div中有一个锚元素。我正在听两个元素点击事件。当用户单击“a”元素时,我需要阻止点击事件冒泡。但我需要保持锚点工作:用户必须被重定向到'href'页面:

HTML:

<div id="myDiv">
    <a id="myLink" href="www.website.com">Click me</a>
</div>

JS:

$("#myLink").click(function() {
    // DO SOME STUFF

    return false;   // To prevent bubble
});

// This event handler has to be called only when the user clicked inside the div, but outside the link
$("#myDiv").click(function() {
    // DO SOME STUFF
});

问题是用户没有被重定向到“www.website.com”。怎么能做到这一点?

1 个答案:

答案 0 :(得分:1)

您没有阻止事件正常冒泡。

$("#myLink").click(function(e) {


    e.stopPropagation(); // this will prevent bubbling.
});

// This event handler has to be called only when the user clicked inside the div, but outside the link
$("#myDiv").click(function() {
    // DO SOME STUFF
});

您可以在此处详细了解event.stopPropagation():http://api.jquery.com/event.stopPropagation/

如果要重定向,则必须使用:

window.navigate('url-goes-here');