开发者

Swap all images on page via one link JQuery

I have to build a site that has multiple color options but it also has to have the ability to give the 'Zoom' impression. This is why I need all images on page so I am able to increase their size.

The only problem I have is I am not sure how t开发者_运维百科o add a certain prefix to all images on the page via one link.

E.G. Click Pink/White and it adds a prefix _pw to all images on the page..

Any help would be great


The other solutions posted so far work, but are horribly inefficient. Here’s a better solution:

var isZoom = false;
$('#some-link').click(function(e) {
  e.preventDefault();
  $('img').each(function() {
    this.src = isZoom ? this.src.replace('_pw.jpg', '.jpg') : this.src.replace('.jpg', '_pw.jpg');
  });
  isZoom = !isZoom;
});

This assumes that all images have the same .jpg extension.

Alternatively, you could use .attr instead of .each:

var isZoom = false;
$('#some-link').click(function(e) {
  e.preventDefault();
  $('img').attr('src', function(i, src) {
    return isZoom ? src.replace('_pw.jpg', '.jpg') : src.replace('.jpg', '_pw.jpg');
  });
  isZoom = !isZoom;
});


// Get all your zoomable images (maybe with some special class to identify them)
// Iterate over them
$('img.specialClass').each(function() {

    // Get original src attribute
    var origSrc = this.src; 

    // Split by slash
    var arraySrc = origSrc.split('/'); 

    // New src attribute is:
    var newSrc = arraySrc.slice(0,-1).join('/') + // all but last parts of URL
    '/pw_' + // with a new prefix
    arraySrc.slice(-1); // and the original file name

    // Finally, set the new src attribute
    this.src = newSrc;
})


There's probably a more concise way of writing it, but it's a simple operation nonetheless:

 $('#pinkButton').click(function()
 {
      $('img').each(function()
      {
           $(this).attr('src', $(this).attr('src') + '_pw');
           // Will take the previous src attribute and add '_pw' in the end.
      });
 });

There will probably need to be some modification to the above to put the suffix in the right spot of the src string, but you get the idea. (basically, making sure the extension gets moved, etc)


$("img").attr('src', function(i,a) {
    return a + '_pw';
});


$('IMG').attr('class','_pw');

Should set all IMG's classnames to "_pw".

i.e:

$('#mybutton').click(function(){
   $('IMG').attr('class','_pw');
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜