[英]How to targeting Specific Elements with Common Classes, using jQuery Toggle?
I'm creating a drop down menu that will be reused many times on a single page. 我正在创建一个下拉菜单,该菜单将在一个页面上重复使用多次。
The following code works great when there's only one drop down menu. 当只有一个下拉菜单时,以下代码非常有用。 But when there are multiple drop downs, clicking a single .dropdown
will result in all the .dd_menu
's on the page being revealed. 但是当有多个下拉菜单时,单击一个.dropdown
将导致页面上的所有.dd_menu
被显示出来。
$(document).ready(function() {
$('.dropdown').click(function(){
$('.dd_menu').toggle();
});
});
<div class="dropdown">
<a class="mini_button" href="#">Actions</a>
<div class="dd_menu">
<a href="http://example.com">Link</a>
<a href="http://example.com">Link</a>
<a href="http://example.com">Link</a>
</div>
</div>
Is there some what to target only the .dd_menu
that is inside the particular .downdown
which was clicked? 有一些什么样的目标只有.dd_menu
是特定的内部.downdown
它被点击?
Limit the selector to the .dd_menu
that is a child of the current clicked .dropdown
div: 将选择器限制为.dd_menu
,它是当前单击的.dropdown
div的子项:
$(document).ready(function() {
$('.dropdown').click(function(){
$('.dd_menu', this).toggle(); // <========== used this as a context.
});
});
jQuery( selector [, context] )
: jQuery( selector [, context] )
:
selector
A string containing a selector expression selector
包含选择器表达式的字符串 context
A DOM Element , Document, or jQuery to use as context context
用作上下文的DOM元素 ,Document或jQuery You can also use the find
function: $(this).find('.dd_menu')
but it exactly the same. 你也可以使用find
函数: $(this).find('.dd_menu')
但它完全一样。 the context selector is calling the find
function. 上下文选择器正在调用find
函数。
你可以尝试:
$(this).children('.dd_menu').toggle();
$(document).ready(function() {
$('.dropdown').on('click', 'a', function(){
$('.dd_menu:eq('+$(this).parent().index()+')').toggle();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.