jquery toggle on multiple divs only working on first element
ive created a page but it's only toggling the first div and the other 2 arent working... can't work out why! Thanks in advance
var levelopen=false;
$(document).ready(function() {
$('开发者_JAVA百科.contentlevel').hide();
$('#levelopener').click(function(){
if(levelopen==false)
{
$('#levelopener').html('[less]');
levelopen=true;
}
else
{
$('#levelopener').html('[more]');
levelopen=false;
}
$(this).next(".contentlevel").slideToggle(100);
return false;
});
});
http://jsfiddle.net/q2qxX/4/
This is because you have several elements with the same id (levelopener
), ids must be unique. Use a class of levelopener
and the selector .levelopener
for the click event.
Also, use $(this)
to refer to current item that's being clicked for the comparisons like you have for the toggling.
You can't have multiple elements with the same id and you should use the this
object when referring to the object calling the method.
http://jsfiddle.net/x8RW6/
var levelopen=false;
$(document).ready(function() {
$('.contentlevel').hide();
$('.levelopener').click(function(){
if(levelopen==false)
{
$(this).html('[-]');
levelopen=true;
}
else
{
$(this).html('[+]');
levelopen=false;
}
$(this).next(".contentlevel").slideToggle(100);
return false;
});
});
EDIT
after some consideration, I've determined the function needs just a few other tweaks. :P
var levelopen=false;
$(document).ready(function() {
$('.contentlevel').hide();
$('.levelopener').click(function(){
if($(this).next(".contentlevel").is(":visible"))
$(this).html('[+]');
else
$(this).html('[-]');
$(this).next(".contentlevel").slideToggle(100);
return false;
});
});
in your html , all your links have the same id -levelopener HTML id's should be unique
It's because you have multiple a
tags with the same id. Switch them to classes and it works perfectly.
http://jsfiddle.net/q2qxX/7/
Updated code based on comment to use this
inside the click function.
you can't have the same ID's in one html page.
Your HTML is not correct IDs must be unique across all elements in a page.
Try this instead...Here is a modified fiddle using a common classname instead of id
http://jsfiddle.net/q2qxX/10/
id
s must be unique so your selector is only grabbing the first one. Change your id to a class and use a class selector in your jQuery.
$('.levelopener').click(function(){
精彩评论