从elements属性替换img src

时间:2011-12-04 20:26:17

标签: jquery toggle image src

如果我的页面上有这个HTML

<img src="samesrc" class="commentimg" name="differentimg1"/>

我可以使用src=属性切换<img> name=的{​​{1}},因此当我点击<img>时,src变为 differentimg1 ,并应用另一个类

<img src="differentimg1" class="commentimg commentimgresize" name="differentimg1"/>

然后再次点击时,html源会返回原始名称

<img src="samesrc" class="commentimg" name="differentimg1"/>

这应该应用于所有图像,但切换时的src应该对应元素name=值。

我已经尝试 http://jsfiddle.net/yusaf/zy5j8/25/

$('.imgreplace').each(function(){
$('.imgreplace').click(function(){
    var replacesrc = $(".commentimg").attr("name");
    $('.commentimg').attr("src", "+replacesrc+");
    $('.commentimg').toggleClass('commentimgresize')
})
});

5 个答案:

答案 0 :(得分:2)

所以在点击时,使src = name,除非它们相等,在这种情况下将src设置回原来的值。诀窍将是记住原始src是什么;数据功能 - 允许您按键存储元素上的任意数据 - 可以帮助您完成此操作。

$(".imgreplace").click(function() {
    if (this.attr("src") !== this.attr("name")) {
       this.data("oldsrc", this.attr("src"));
       this.attr("src", this.attr("name"));
    } else
       this.attr("src", this.data("oldsrc"));
    this.toggleClass('commentimgresize');
});

答案 1 :(得分:2)

$('.commentimg').click(function(){
    var replacesrc = $(this).attr("name");
    $(this).attr("src", replacesrc).toggleClass('commentimgresize');
});

答案 2 :(得分:2)

这有效

$('.commentimg').click(function(){
    var a = $(this).attr('src');
    var b = $(this).attr('name');
    $(this).attr('src',b).attr('name', a);
});

示例: http://jsfiddle.net/jasongennaro/zy5j8/26/

说明: Onclick抓取srcname属性,撤消它们。

答案 3 :(得分:1)

你不能添加这样的变量,试试:

var replacesrc = $(".commentimg").attr("name");
$('.commentimg').attr("src", replacesrc);

此外,使用网址作为名称可能是最好的想法。

答案 4 :(得分:0)

name用于网址是错误的(谷歌,对于其中一个,会感到困惑)。

相反,请尝试使用data-属性,如下所示:

<img
  src="url1" 
  class="commentimg"
  data-src2="url2"/>

$('.commentimg').click(function(){
    var temp_src = $(this).attr('data-src2');
    $(this)
        .attr('data-src2', $(this).attr('src'))
        .attr('src', temp_src)
        .toggleClass('commentimgresize');
});

看到它正常工作here

相关问题