在 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>
在 jQuery 中,如果我想检查用户是否单击了页面中的任何链接,我使用以下代码:
$('a').click(function() {
// do something
});
如果用户仅单击特定 div 中的链接,如何启动函数?我想要一个函数,如果用户仅单击名为“main_menu”和“second_menu”的 div ID 中的任何链接,而不是“menu_outside”中的任何链接,则该函数会启动。
Depending on what exactly you want to do, you can bind the event handler to those links only, using the descendant [docs] http://api.jquery.com/descendant-selector/ and multiple [docs] http://api.jquery.com/multiple-selector/ selectors:
$('#main_menu a, #second_menu a').click(function() {
// link inside #main_menu or #second_menu
});
如果您不想对两者执行相同的操作,则必须单独绑定事件处理程序。
You could also check dynamically whether the link is a descendant of any of these element, with closest [docs] http://api.jquery.com/closest/:
$('a').click(function() {
if($(this).closest("#main_menu").length) {
// inside #main_menu
}
if($(this).closest("#second_menu").length) {
// inside #second_menu
}
//...
});
但这会带来额外的开销。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)