Okay I've tried multiple things and looked for answers to this and I can't seem to get it to work. What I'm trying to do is there are some dynamically generated images, so I don't know how many images there will be at any time. Each image has some associated information that I store in a seperate div. What I want to do is attach a click event to each image that will unhide the div that has the associated content in it.
I've tried looping with both a for loop and a while loop, to no avail. What happens in both is they attach the click event fine, but no matter the image clicked on, the same div always opens, no the div associated with the image.
var cnt = jQuery('#container img').length;
cnt = cnt - 1;
var i = 0
for(i=0; i<=cnt; i++) {
jQuery('#container img').eq(i).click(function() {
jQuery('.movie' + 1).slideDown();
jQuery('#sort').hide();
});
}
while(i<=cnt) {
jQuery('#container img').eq(i).click(function() {
jQuery('.movie' + i).slideDown();
jQuery('#sort').hide();
});
i++
}
Above is the two different variations I've tried. The second doesn't have the variables defined on here but in my code they do. What I'm doing is getting a count of how many images I have (var cnt) and then using that to loop through the correct number of times. I'm assuming something must be getting messed up in the click function, as it attaches it to each image fine but gets the wrong div.
EDIT:
As per some comments, I tried changing my structure to be something like this:
<div id="container">
<img />
<img />
<div class="expanded">
// Info Goes Here
</div>
<div class="expanded">
// Info Goes Here
</div>
</div>
I then tried the code:
jQuery(document).ready(function() {
jQuery('#container img').click(function () {
jQuery(this).next('div.expanded').show();
});
});
But it doesn't work either. The first image does nothing and the second shows the wrong div.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…