Jquery Click Variable Loop
I am working on getting assigning a dynamic variable within Jquery in which the buttons could change to be more or less 开发者_运维知识库so I figured a loop would be best. (that rimes oo god it's gotten to be that fun). So here is the break down in which I can not seem to get to figured out.
$(".acc_trigger").each(function(j) {
$("#accord" + j).click(function() {
$(".selectedimg").hide('drop', { direction: 'down' }, 1000);
$(".selectedimg").removeClass("selectedimg");
$("#accordimg"+ j ).addClass("selectedimg");
$("#accordimg"+ j ).show('drop', { direction: 'up' }, 1000);
});
});
For each class which are buttons add a click in which the id has a number to the end of it which removes the class selected but then replaces with the same number used in the id above. I can't get this to work and have thought about using loops but when I do it goes the same number of times the loop is for. I'm trying to just create a number of click functions that allows for the variable to be dynamic to make it so I can have more or less buttons.
I tested your code and it works fine, here's the example I made. (minus your plugin)
http://jsfiddle.net/5tLZk/3/
Your code should work just fine, if the options for the show
and hide
works.
I tested your code, only with the options for the show
and hide
reduced (as I don't know what plugin you use for that custom easing), and it works just fine:
http://jsfiddle.net/EJyn5/
Edit:
Judging by your comment to Brandons answer; perhaps you are starting your elements with index 1 instead of index 0?
If you want to avoid the loop, this should work (assuming that the .img elements are between the .acc_trigger elements).
<div class="acc_trigger" id="accord0">0</div>
<div class="img" id="accordimg0">0</div>
<div class="acc_trigger" id="accord1">1</div>
<div class="img" id="accordimg1">1</div>
<div class="acc_trigger" id="accord2">2</div>
<div class="img" id="accordimg2">2</div>
$(".acc_trigger").click(function() {
$(".selectedimg").hide(1000);
$(".selectedimg").removeClass("selectedimg");
$(this).next(".img").addClass("selectedimg");
$(this).next(".img").show(1000);
});
You can try it out here: http://jsfiddle.net/EJyn5/.
You should be able to use jQuery's live function to do this without having to use loops or anything.
$('.CssClassThatAllYourButtonsShare').live('click', function() {
$(".selectedimg").hide('drop', { direction: 'down' }, 1000);
$(".selectedimg").removeClass("selectedimg");
//Extract the number from the current ID
var j = $(this).attr('id').match(/\d+$/);
$("#accordimg"+ j).addClass("selectedimg");
$("#accordimg"+ j).show('drop', { direction: 'up' }, 1000);
});
Documentation on Live: http://api.jquery.com/live/
Description: Attach a handler to the event for all elements which match the current selector, now and in the future.
精彩评论