jQuery simple for loop
What i have is a UL generated with PHP with 9 li items. Each have a class from 1 to 9.
I also have 9 divs generated with PHP also having classes from 1 to 9. I'm trying to use jQuery so that when someone clicks a li item, its corresponding div gets shown/hidden...
ie. click li class 3, show div class 3.
I have this:
for (var i = 1; i <= 9; i++){
$("li." + i).click(function(){
$("div." + i).toggle();
});
}
However its not quite working. Can anyone see why it may not be?
<ul class="featureItems">
<li class='1'>Seo</li>
<li class='2'>Social Media</li>
<li class='3'>Internet Marketing</li> 开发者_如何学Python
<li class='4'>Lead Generation</li>
<li class='5'>Appointment Setting</li>
<li class='6'>Telesales</li>
<li class='7'>Copyright</li>
<li class='8'>Promotions</li>
<li class='9'>Website Design</li>
</ul>
<div id="featuredItem">
<div class='1 featureText'>i'm seo text</div><div class='2 featureText'>i'm social media text</div><div class='3 featureText'>i'm internet marketing text</div><div class='4 featureText'>i'm lead generation text</div><div class='5 featureText'>i'm appointment setting text</div><div class='6 featureText'>i'm telesales text</div><div class='7 featureText'>i'm copyright text</div><div class='8 featureText'>i'm promotions text</div><div class='9 featureText'>i'm website design text</div> </div>
</div>
Outputted HTML!
EDIT 2: this was the answer that solved it:
$('li').click(function(evt)
{
$('div.' + $(this).attr('class')).toggle();
});
This won't work if your li
s have more than one class. If this is an issue, I'd consider using something else to pass that information in, like an HTML5 data
attribute or the rel
attribute.
Not sure if it is your problem, but it is almost always a bad idea to start identifiers (in this case class names but ids could have this problem too) with a number. I suggest you use the names c1, c2, c3, c4 etc. It may be that somewhere in your code the number names are being converted to numbers and not strings.
You might also consider even better names, but I expect just starting the names with the letter 'c' will help.
The problem is that when you call the function inside the click the value of i is 10. You need a closure:
for (var i = 1; i <= 9; i++){
(function (i){
$("li." + i).click(function(){
$("div." + i).toggle();
});
})(i)
}
http://jsfiddle.net/bicccio/prTH9/
精彩评论