Javascript 如何响应容器&x27;点击事件?
假设我有一个包含2个链接的列表项:Javascript 如何响应容器&x27;点击事件?,javascript,jquery,Javascript,Jquery,假设我有一个包含2个链接的列表项: <li> <a href="foo.htm">Foo</a> <a href="bar.htm">Bar</a> </li> 如果用户单击“Foo”,我想将用户发送到Foo.htm。如果用户单击或“Bar”的任何部分,我想将用户发送到Bar.htm。我担心如果我在上附加一个点击事件监听器,点击“Foo”会将用户发送到bar.htm。您是否尝试过使用event.stopP
<li>
<a href="foo.htm">Foo</a>
<a href="bar.htm">Bar</a>
</li>
如果用户单击“Foo”,我想将用户发送到Foo.htm。如果用户单击
或“Bar”的任何部分,我想将用户发送到Bar.htm。我担心如果我在
上附加一个点击事件监听器,点击“Foo”会将用户发送到bar.htm。您是否尝试过使用event.stopPropagation()
您尝试过使用event.stopPropagation()吗
下面的代码应该可以解决您的问题
$("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.
});
下面的代码应该可以解决您的问题
$("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.
});
您必须在Foo和Bar的处理程序上使用
event.stopPropagation()
,请参阅有效的解决方案
为了方便起见,将JSFIDLE代码粘贴到此处:
HTML:
您必须在Foo和Bar的处理程序上使用
event.stopPropagation()
,请参阅有效的解决方案
为了方便起见,将JSFIDLE代码粘贴到此处:
HTML:
像这样的。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";
}
});
像这样的。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";
}
});
似乎很好似乎很好
$("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";
}
});