1

假设我有一个包含 2 个链接的列表项:

<li>
   <a href="foo.htm">Foo</a>
   <a href="bar.htm">Bar</a>
</li>

如果用户单击“Foo”,我想将用户发送到 foo.htm。如果用户单击“栏”的任何部分<li>或“栏”,我想将用户发送到 bar.htm。我担心如果我将点击事件侦听器附加到<li>点击“Foo”的点击会将用户发送到 bar.htm。

4

4 回答 4

5

您是否尝试过使用 event.stopPropagation()

$("a[href='foo.html']").click(function (event) {
    event.stopPropagation()
});
于 2012-09-18T16:50:29.950 回答
2

像这样的东西。stopPropagation 不应该是必需的,因为我知道你希望链接到指定的位置。

$("li").click(function(e){
    //just in case the click on li is processed before link click
    if($("a[href='foo.html']").is(e.target)){
        window.location.href = "foo.html";
    }
    else {
        window.location.href = "bar.html";
    }
});
于 2012-09-18T17:24:08.953 回答
0

以下代码应该可以解决您的问题。

$("li").click(function (e) {
            if(e.target.nodeName == "A" && e.target.href.indexOf("foo.html") !== -1){
                //send foo.html
            }
            event.stopPropagation();
            // send bar.html
           return false.
        });
于 2012-09-18T17:11:43.217 回答
0

您必须event.stopPropagation()在 Foo 和 Bar 的处理程序上使用,请参阅此处的工作解决方案

为方便起见,在此处粘贴 jsfiddle 代码

HTML:

<li id="l1">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   <a href="http://www.google.es/q=foo" id="foo">Foo</a>
   <a href="http://www.google.es/q=bar" id="bar">Bar</a>
</li>

JAVASCRIPT:

$('#foo').bind('click',function(event) {
    event.stopPropagation();
});
$('#bar').bind('click',function(event) {
    event.stopPropagation();
});
$('#l1').bind('click',function() {
    window.location.href = $('#bar').attr('href');
});​
于 2012-09-18T17:15:48.030 回答