javascript jQuery - 如何检查是否在特定 DIV 中单击了任何链接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7173604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - How check if any link was clicked in a specific DIV?
提问by Lucas
In HTML code my page contains:
在 HTML 代码中,我的页面包含:
<div id="main_menu">
<a href="#" id="login">Link1</a>
<a href="#" id="logout">Link2</a>
</div>
<div id="second_menu">
<a href="#" id="information">Link info</a>
<a href="#" id="profile">My profile</a>
</div>
<div id="menu_oustide"><a href="#" id="something">Link1</a></div>
In jQuery if I want to check if the user clicked any link in page I use this code:
在 jQuery 中,如果我想检查用户是否点击了页面中的任何链接,我使用以下代码:
$('a').click(function() {
// do something
});
How can I start a function if the user clicked only on links in specific div? I would like to have a function that starts if a user clicked any link only in div ID named "main_menu" AND "second_menu", but not in "menu_outside".
如果用户仅单击特定 div 中的链接,如何启动功能?我想要一个函数,如果用户只在名为“main_menu”和“second_menu”的 div ID 中单击任何链接,而不是在“menu_outside”中单击任何链接,该函数就会启动。
回答by Felix Kling
Depending on what exactly you want to do, you can bind the event handler to those links only, using the descendant[docs]and multiple[docs]selectors:
根据您到底想要做什么,您可以使用后代[docs]和多个[docs]选择器将事件处理程序仅绑定到这些链接:
$('#main_menu a, #second_menu a').click(function() {
// link inside #main_menu or #second_menu
});
If you don't want to perform the same action for both, you have to bind the event handler individually.
如果不想对两者执行相同的操作,则必须单独绑定事件处理程序。
You couldalso check dynamically whether the link is a descendant of any of these element, with closest
[docs]:
您还可以使用closest
[docs]动态检查链接是否是这些元素中的任何一个的后代:
$('a').click(function() {
if($(this).closest("#main_menu").length) {
// inside #main_menu
}
if($(this).closest("#second_menu").length) {
// inside #second_menu
}
//...
});
But that introduces an additional overhead.
但这会带来额外的开销。
回答by Anil
use this to select the div and ahref you want.
用它来选择你想要的 div 和 ahref。
$('#second_menu a').click(function(){
// This will select the a href's only in the second menu.
// basically, in div id "#second_menu" select all "a" elements.
});