I need to toggle(show/hide) the <p>
which is the sub-element of the clicked <li>
, while all other <p>
s should should hide. I was able to do this.
But clicking on the same element(which is now showing) does not hide. How to achieve this ?
$(document).ready(function(){ $("p").hide(); $("li").click(function(){ $("p").not(this).hide(200); $("p", this).toggle(200); }); });
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> </head> <body> <ul> <li><a>q1</a> <p>a1</p> </li> <li><a>q2</a> <p>a3</p> </li> <li><a>q3</a> <p>a3</p> </li> <li><a>q4</a> <p>a4</p> </li> </ul> </body> </html>
You need to pass the p
elements to be excluded to not()
, you are now passing this
which is referring to the li
element
$(document).ready(function() { $("p").hide(); $("li").click(function() { var $ps = $("p", this).stop(true).toggle(200); $("p").not($ps).stop(true).hide(200); }); });
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> </head> <body> <ul> <li><a>q1</a> <p>a1</p> </li> <li><a>q2</a> <p>a3</p> </li> <li><a>q3</a> <p>a3</p> </li> <li><a>q4</a> <p>a4</p> </li> </ul> </body> </html>
$(document).ready(function(){
$("p").hide();
$("li").click(function(){
$(this).find('p').toggle(200);
$(this).siblings('p').hide(200);
});
});
DEMO Try doing like this
Use this simple logic :
$(document).ready(function(){
$("p").hide();
$("li").click(function(){
$("p").not(this).hide(200);
if($("p",this).is(":visible")){
$("p", this).hide(200);}
else{
$("p", this).show(200);}
});
});
Check this fiddle
Change your jQuery code like
$(document).ready(function(){
$("p").hide();
$("li").click(function(){
$("p").not($(this).find("p")).hide(200);
$(this).find("p").toggle(200);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.