当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Jquery .each, but only that current element

问题描述:

I'm using the following script

$('.cat_glass_thumbs ul li').each(function(){

$(this).click(function(){

orig_src = $(this).attr('data-orig');

$('.cat_glass_thumbs a img').attr('src', orig_src);

});

});

I have loop that outputs multiple divs, all of them the same structure, different content.

Right my jquery works ".cat_glass_thumbs" div, if I flick on the li, it will update the src in every .cat_glass_thumb, instead of just updating the one I am in.

Tips/pointers would be appreciated

html of each for reference:

<div class="cat_glass_thumbs">

<a href="" title="Black/Silver" class="product-image thumbnail">

<span class="main_image">

<img src="t/2064-a-blk-slv-52-angle.jpg" alt="Black/Silver">

</span>

</a>

<ul id="thumbs_container">

<li class="img_thumbs" data-orig="/t/-2064-a-blk-slv-52-angle.jpg">

</li>

<li class="img_thumbs" data-orig="/t/-2064-a-blk-slv-52-front.jpg">

</li>

<li class="img_thumbs" data-orig="/t/-2064-b-blk-gld-52-angle.jpg">

</li>

</ul>

</div>

网友答案:

Drop the each, it's useless in this case (jQuery automatically does it for you):

$('.cat_glass_thumbs ul li').click(function(){
    var orig_src = $(this).data('orig');
    $('a img', this).attr('src', orig_src);
});

JS Fiddle Demo

Note that I used $('a img', this) in the form of $( selector [, context ] ) described in the jQuery documentation.


Edit

Your JS code alone made me think of another HTML structure. To fit the one you posted, you need to target the image in the parent .cat_glass_thumbs using $.closest():

$('.cat_glass_thumbs ul li').click(function(){ 
    var orig_src = $(this).data('orig');
    $('a img', $(this).closest('.cat_glass_thumbs')).attr('src', orig_src);
});

Updated JS Fiddle

$.closest()

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

网友答案:

I think this will work:

$('.cat_glass_thumbs ul li').each(function(){
    $(this).click(function(){
        orig_src = $(this).attr('data-orig');
        $(this).find("a img").attr('src', orig_src);
    });
});
网友答案:

$(this) element in your example points to all '.cat_glass_thumbs ul li', you must pass variable to $.each

$('.cat_glass_thumbs ul li').each(function($currentElement){
    $currentElement.click(function(){
        orig_src = $(this).attr('data-orig');
        $(this).children("img").attr('src', orig_src);
    });
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: