jQuery - 如何检查某个特定DIV中是否有链接被点击? [英] jQuery - How check if any link was clicked in a specific DIV?
问题描述
< div id =main_menu>
< a href =#id =login> Link1< / a>
< a href =#id =logout> Link2< / a>
< / div>
< div id =second_menu>
< a href =#id =信息>链接信息< / a>
< a href =#id =profile>我的个人资料< / a>
< / div>
< div id =menu_oustide>< a href =#id =something> Link1< / a>< / div>
在jQuery中,如果我想检查用户是否点击了页面中的任何链接,我使用下面的代码:
$('a')。click(function(){
//做某事
});
如果用户只点击特定div中的链接,我该如何启动一个函数?
根据你想要做什么,你可以只使用 后代 [docs] 和 多个 [docs] 选择器:
$('#main_menu点击(函数(){
//在#main_menu或#second_menu
}中的链接);
如果您不想为两者执行相同的操作,您必须绑定事件处理程序
您也可以动态检查链接是否为这些元素的后代,并且 最接近
[docs] :
$ $ $ $ $ $ $ $ $' ).length){
//在#main_menu
中}
if($(this).closest(#second_menu)。length){
// inside# second_menu
}
// ...
});
但是这会带来额外的开销。
In HTML code my page contains:
<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:
$('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".
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:
$('#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 could also check dynamically whether the link is a descendant of any of these element, with 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.
这篇关于jQuery - 如何检查某个特定DIV中是否有链接被点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!