2011-03-18 24 views
0

我必须构建一个具有多种颜色选项的网站,但它也必须能够提供“缩放”印象。这就是为什么我需要页面上的所有图像,所以我能够增加它们的大小。通过一个链接在页面上交换所有图像JQuery

我唯一的问题是我不知道如何通过一个链接添加一个特定的前缀到页面上的所有图像。

E.G.点击粉红/白色,并将其添加一个前缀_pw所有图像在页面上..

任何帮助将是巨大的

+0

前缀添加到所有图像?改变所有图像的风格?改变图像的来源? – Curlas 2011-03-18 12:01:34

+0

是为图像本身添加前缀,例如images/banner_pw.jpg – 2011-03-18 12:02:52

回答

1

的其它解决方案公布至今的工作,但效率极其低下。这里有一个更好的解决方案:

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; 
}); 

这是假设所有的图像具有相同的.jpg扩展。

或者,你可以使用.attr代替.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; 
}); 
+1

好短简单干净。 – Loktar 2011-03-18 12:08:30

+0

感谢您的作品完美,但当我再次点击链接时,它会打破图像,有没有办法让他们点击它删除前缀? – 2011-03-18 12:16:23

+0

@John White我已经更新了我的答案,允许切换回来。 – 2011-03-18 12:23:36

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

应该将所有IMG的类别名称为“_pw”。

即:

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

对不起我解释错误,我需要添加前缀到图像本身E.G. images/banner_pw.jpg – 2011-03-18 12:00:11

+0

'jQuery#onclick'没有定义,所以你的第二个例子根本不起作用。 – 2011-03-18 14:46:04

0

有可能写它的一个更简洁的方式,但它是一个简单的操作仍然:

$('#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. 
     }); 
}); 

有可能需要一些修改上面放后缀在src字符串的右侧,但你明白了。 (基本上,确保扩展被移动等)

+0

非常感谢你的工作:) – 2011-03-18 12:11:13

+0

你忘了阻止点击事件的默认操作。另外,你正在''each'中实例化两个新的jQuery对象,而不需要任何东西。这是一个巨大的表现。 – 2011-03-18 12:11:52

0
$("img").attr('src', function(i,a) { 
    return a + '_pw'; 
}); 
1
// 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; 
}) 
+1

使用'this.src'而不是'$(this).attr('src')'和'this.src = newSrc'而不是'$(this).attr('src',newSrc)'。 – 2011-03-18 12:13:49

相关问题