开发者

Jquery apply one source image to another

I've got a larger slider image and a smaller "thumbnail" image. I have this code so far:

 $j(".slider-img").each( function(){
  var slideSource = $j(this).attr("src");
   $j(".slider-thumb").each(function() {
    $j(this).attr("src", slideSource); 
   });
 });

But its giving me the image from the first slide for all of the thumbnails. So I want to take the source from each .开发者_如何学运维slider-img and apply it to each .slider-thumb. Ideas?


Presuming the .slider-img that corresponds to a .slider-thumb is in the same position in the document, relative to the others with that class, you can use this:

var thumbs = $j('.slider-thumb');
$j('.slider-img').each(function(i) { // i is the position in the set
    thumbs.eq(i).attr('src', this.src); // set the src attribute of the element with position i in the thumbs set to the src of this element
});


You need a way to find the corresponding thumb when you're in your image. It can be a "rel" attribute on your parent image (or on the thumb), it's not very official-w3c-clean but it's used :-)

You can as well try to find the thumb by "walking in the DOM with the travsering functions http://api.jquery.com/category/traversing/ it could make something like that:

 $j(".slider-img").each( function(){
   var slideSource = $j(this).attr("src");
   var thethumb = $j(".slider-thumb",
     $j(this).parent('div')
     .next()
     .child('table:first')
     .next()
   );
   thethumb.attr("src", slideSource);
 });

Here I use a context to the $j(".slider-thumb", context) selector. The context is a part of the DOM where you're sure the only image with class "slider-thumb' is your target.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜