Look at the code:
<div class="test">
<p><a href="#">1</a><a href="#">2</a><a href="#">3</a></p>
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<script language="javascript" type="text/javascript">
$(".test a").each(function(index,element){
$(element).click(function(){
$(element).toggleClass("hover"); // here works well
$(".test div:eq(index)").slideToggle(); // here words wrong!
});
});
</script>
above code, i think it should work well,but i am wrong. i do not know why.
the second event:the “div” only slidetoggle the first, other div do not slidetoggle, whenever you click which “a” tag.
another way is wrong the same:
<script language="javascript" type="text/javascript">
$(".test a").click(function(){
x = $(this).index();
$(this).toggleClass("hover"); // here works well
$(".test div:eq(x)").slideToggle(); // here words wrong!
});
</script>
by the way, i test .get(index) method too, the browser says: it does not support the method!
is there a master to solve this difficulty?
guys! Through testing again and again, i finally figured out. Let me show the correct code:
plan A:
<script language="javascript" type="text/javascript">
$(".test a").each(function(index,element){
$(element).click(function(){
$(element).toggleClass("hover");
$(".test div").eq(index).slideToggle();
});
});
</script>
plan B:
<script language="javascript" type="text/javascript">
$(".test a").click(function(){
x = $(this).index();
$(this).toggleClass("hover");
$(".test div").eq(x).slideToggle();
});
</script>
OR Just:
<script language="javascript" type="text/javascript">
$(".test a").click(function(){
$(this).toggleClass("hover");
$(".test div").eq($(this).index()).slideToggle();
});
</script>
plan C: come from @Šime Vidas `s method
<script language="javascript" type="text/javascript">
$(".test").on("click","a",function(){
$(this).toggleClass("hover");
$(this).parent().siblings().eq($(this).index()).slideToggle();
});
</script>
I test :eq(" + index + ") it does not work. but .eq(index) works well!
is that mean in selector :eq(n),n could not be variable, but, in method .eq(n), n can be variable?
I test .on method, it does not work with jquery-1.6.4.min, but works well with jquery-1.7.1.min.
There is another interesting thing:Plan B, the first code, the x variable is always be 0 in some more complicated condition, but the sencond code has no this problem. i can not figure this out yet.
thank you all guys, for all your methods and help, without you, i could not figure this out.
Try this: