2011-08-24 48 views
5

在HTML代码我的网页包含:jQuery - 如何检查特定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="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”中。

回答

10

取决于正是你想做的事,你可以将事件处理程序绑定到只有那些链接,使用descendant[docs]multiple[docs]选择:

$('#main_menu a, #second_menu a').click(function() { 
    // link inside #main_menu or #second_menu 
}); 

如果你不想进行了同样的动作两者都必须分别绑定事件处理程序。

可以也动态地检查网络连接是否是这些元素的后代,与closest[docs]

$('a').click(function() { 
    if($(this).closest("#main_menu").length) { 
     // inside #main_menu 
    } 
    if($(this).closest("#second_menu").length) { 
     // inside #second_menu 
    } 
    //... 
}); 

但是,引入了额外的开销。

+1

同样,如果您有机会在未来添加更多菜单,可能会更好地使用类而不是列出div ID – ollie

1

用它来选择你想要的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. 
}); 
相关问题