2011-12-04 93 views
2

如果我有我的网页上这个网站更换IMG SRC从元素属性

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

怎样的onclick可以切换的<img>src=name=属性,所以当我点击<img>的SRC成为differentimg1 ,并且点击时,再次html源代码返回到原来的即

另一个类应用

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

,然后

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

回答

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/

说明:Onclicksrcname属性,反向它们。

+0

这太棒了,只是错过了一件事,但我明白了,http://jsfiddle.net/yusaf/zy5j8/31/,非常感谢。 –

+0

很高兴为你效劳,@Yusaf! –

+1

@Yusaf - 这确实比我的回答更好 - 它会覆盖name属性,但这并不重要。名称对img没有任何作用,实际上这个标签(和其他)已被**弃用**。将来,如果您需要占位符属性,则可以使用html5数据属性 - data-swapsrc ='...'它也是跨浏览器安全的 –

2

于是就点击,使SRC =名称,除非他们是平等的,在这种情况下,设置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

你不能添加这样一个变量,尝试:

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

而且,使用URL作为名字大概is'nt最好的想法。

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

对网址使用name是错误的(Google对此会感到困惑)。

相反,尝试使用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