开发者

How to find correct image by using jquery index

I would need to find a certain image in a div and show it. But the the thing is that I click on a different image. Here's the code:

<div id="images">
<img src="but1.jpg" alt="" />
<img src="but2.jpg" alt="" />
<img src="but3.jpg" alt="" />
<img src="but4.jpg" class="zoomImage" alt="" />
<img src="but5.jpg" class="zoomImage" alt="" />
<img src="but6.jpg" alt="" />
</div>

<div id="images2" style="display:none;">
<img src="butB4.jpg" alt="" />
<img src="butB5.jpg" alt="" />
</div>

Now if I click some of the images that has the class zoomImage, I would like to show (give display:block;) to image that is in images2 div. For example if I would click on

 <img src="but4.jpg"开发者_如何转开发 class="zoomImage" alt="" />

it should show up

<img src="butB4.jpg" alt="" />

and if I would click on

<img src="but5.jpg" class="zoomImage" alt="" />

it should show up

<img src="butB5.jpg" class="zoomImage" alt="" />

and then if I would click on

<img src="but6.jpg" alt="" />

nothing should happen.


Try this

$('#images img.zoomImage').each(function(i) {
    $(this).data("index", i).click(function(){
         $('#images2').show().find("img").hide().eq($(this).data("index")).show();
    });
});


Try something like this, that matches the images in #images with the class zoomImage and tries to find an image with the same number in #images2 and .show() it.

$('#images img.zoomImage').click(function() {
    var imageNo = $(this).attr('src').replace(/^.*(\d+)\.jpg$/, '$1');
    $('#images2 img[src="butB' + imageNo + '.jpg"').show();
});

If, as suggested by you in comments, the image numbers are not consistent. But the images appear in the #images2 DIV in the same order as images with the .zoomImage class appear in the #images DIV above, then you could use the following code.

$('#images img.zoomImage').click(function() {
    var imageNo = $('#images img.zoomImage').index(this);
    $('#images2 img:eq(' + imageNo + ')').show();
});

If you wish to be able to close the images with a subsequent click, use .toggle() instead of .show().


Made the response so that it corresponds to your latest comments:

HTML:

<div id="images">
    <img src="but1.jpg" alt="1" />
    <img src="but2.jpg" alt="2" />
    <img src="but3.jpg" alt="3" />
    <img src="but4.jpg" class="zoomImage" alt="4" />
    <img src="but5.jpg" class="zoomImage" alt="5" />
    <img src="but6.jpg" alt="6" />
</div>

<div id="images2">
    <img src="butB4.jpg" alt="B4" />
    <img src="butB5.jpg" alt="B5" />
</div>

CSS:

#images2 > img {
    display: none;
}

JavaScript:

$(document).ready(function() {

    $('#images > img.zoomImage').each(function(index) {
        var imageNumber = (index + 1);
        $(this).click(function() {
            $('#images2 > img:nth-child(' + imageNumber + ')').show();
        });
    });
});

jsFiddle

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜