jQuery双功能每个 [英] jquery double function each
问题描述
我不止一次地获得以下HTML代码块
I have the following block of HTML code more than once
<div id="page_1" class="page">
<div class="imageDetail_bg">
<img src="../_img/detail_car.jpg" alt="" id="car_detail" class="car_detail"/>
</div><!-- imageDetail-->
<div id="listThumbs">
<div id="thumbsContainer_1" class="thumbsContainer">
<div id="areaThumb" class="areaThumb">
<div id="posThumb_1" class="posThumb">
<img src="../_img/detail_car.jpg" class="detail_img" alt="">
</div>
</div><!--areaThumb-->
<div id="areaThumb" class="areaThumb">
<div id="posThumb_2" class="posThumb">
<img src="../_img/detail_car.jpg" class="detail_img" alt="" />
</div>
</div><!--areaThumb-->
...
...
...
</div><!--listThumbs-->
</div><!--page-->
以及以下jQuery代码:
and the following jQuery code:
$('.page').each(function(i) {
$('.areaThumb').each(function(j) {
$('.detail_img').eq(j).click(function(){
$('.car_detail').eq(i).attr('src', $(this).attr('src'));
});
});
});
我想做的是:每页都有一个拇指块,当我单击任何拇指时,#car_detail中的图像将替换为我单击的拇指图像.现在,我可以执行此操作,但是在所有页面中都将替换#car_detail图像.我没有为每个页面单独执行操作.每次点击都会在所有页面上执行操作.
What I want to do is: For each page there's a block of thumbs, and when I click in any thumb, the image in #car_detail is replaced by the image of the thumb I clicked. At this moment I can do this, BUT the #car_detail image is replaced in all pages. I'm not getting individually actions for each page. Every click make the action occurs in all pages.
有人可以告诉我我在做什么错吗? 谢谢
Can anyone tell me what I'm doing wrong? Thanks
推荐答案
您无需遍历jquery选择器结果的每个元素即可绑定单击事件.
而且您缺少thumbsContainer div的关闭div,请在每个div之前添加它.
You need not iterate through each element of the jquery selector result to bind a click event.
And you are missing a closing div for thumbsContainer div, add that before each .
此外,如果您有一个ID为car_detail的元素,则应使用#car_detail
而不是.car_detail
Also if you have an element with id car_detail then you should use #car_detail
instead of .car_detail
工作示例@ http://jsfiddle.net/2ZQ6b/
尝试一下:
$(".page .areaThumb .detail_img").click(function(){
$(this).closest("div.page").find('.car_detail').attr("src", this.src);
});
如果.detail_img元素用于car_detail图像,则可以将以上代码简化为:
If the .detail_img elements are being used for the car_detail image then you can simplify the above code to:
$(".detail_img").click(function(){
$(this).closest("div.page").find('.car_detail').attr("src", this.src);
});
这篇关于jQuery双功能每个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!