[英]Not able to hide/show the div on mouse click
I have a div contents of which are dynamically generated. 我有一个div内容,它是动态生成的。 I am trying to implement hide/show facility.
我正在尝试实现隐藏/显示功能。 It kinda works but I am looking at "Hide/show only the div that's clicked."
有点用,但是我在看“隐藏/只显示被点击的div”。
HTML 的HTML
<div class="showmenu">First Div</div>
<div class="menu" style="display: none;">
<ul>
<li>Val1</li>
<li>Val2</li>
<li>val3</li>
</ul>
</div>
<div class="showmenu">Second Div</div>
<div class="menu" style="display: none;">
<ul>
<li>val4</li>
<li>val5</li>
<li>val6</li>
</ul>
</div>
JavaScript 的JavaScript
$(document).ready(function() {
$('.showmenu').click(function() {
$('.menu').slideToggle("fast");
});
});
Use relative looks up for the menu
item, instead of a document wide look up( $('.menu')
). 使用相对查找来查找
menu
项,而不是进行文档范围内的查找( $('.menu')
)。
In your case the showmenu
and menu
items are next siblings, so you can use .next() 在你的情况
showmenu
和menu
项旁边的兄弟姐妹,所以你可以使用的.next()
$(document).ready(function() { $('.showmenu').click(function() { $(this).next('.menu').slideToggle("fast"); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="showmenu">First Div</div> <div class="menu" style="display: none;"> <ul> <li>Val1</li> <li>Val2</li> <li>val3</li> </ul> </div> <div class="showmenu">Second Div</div> <div class="menu" style="display: none;"> <ul> <li>val4</li> <li>val5</li> <li>val6</li> </ul> </div>
You need to find the .menu
element related to the element which was clicked. 您需要找到与
.menu
元素相关的.menu
元素。 To do that you can traverse from the element that raised the event using the this
keyword and the next()
method. 为此,您可以使用
this
关键字和next()
方法遍历引发事件的元素。 Try this: 尝试这个:
$('.showmenu').click(function () {
$(this).next('.menu').slideToggle("fast");
});
Use this
: 使用
this
:
$(this)
inside the click event handler is the menu that is clicked. click事件处理程序中的
$(this)
是被单击的菜单。 next
will give menu associated with it. next
将给出与其关联的菜单。
$(document).ready(function() {
$('.showmenu').click(function() {
$(this).next('.menu').slideToggle("fast");
});
});
Demo: http://jsfiddle.net/tusharj/APA2S/4502/ 演示: http : //jsfiddle.net/tusharj/APA2S/4502/
Your looking for jQuery next() 您在寻找jQuery next()
$(document).ready(function() { $('.showmenu').click(function() { $(this).next('.menu').slideToggle("fast"); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <div class="showmenu">First Div</div> <div class="menu" style="display: none;"> <ul> <li>Val1</li> <li>Val2</li> <li>val3</li> </ul> </div> <div class="showmenu">Second Div</div> <div class="menu" style="display: none;"> <ul> <li>val4</li> <li>val5</li> <li>val6</li> </ul> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.