【问题标题】:Replace img src from elements attribute从元素属性替换 img src
【发布时间】:2012-01-12 18:46:23
【问题描述】:

如果我的页面上有这个 html

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

如何在点击时切换&lt;img&gt;src=name= 属性,所以当我点击&lt;img&gt; 时,src 变为differentimg1,并应用另一个类

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

然后当再次单击时,html 源将返回到原始 ie

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

【问题讨论】:

    标签: jquery toggle image src


    【解决方案1】:

    这行得通

    $('.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 属性,反转它们。

    【讨论】:

    • 这太棒了,只是错过了一件事,但我明白了,jsfiddle.net/yusaf/zy5j8/31,非常感谢。
    • @Yusaf - 这确实是比我更好的答案 - 它覆盖了 name 属性,但这并不重要。 Name 对 img 没有任何作用,实际上对于这个标签(和其他标签)已弃用。以后如果需要占位符属性,可以使用html5的数据属性——data-swapsrc='...' 也是跨浏览器安全的
    【解决方案2】:

    使用 name 作为 URL 是错误的(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

    【讨论】:

      【解决方案3】:

      所以在单击时,使 src = name,除非它们相等,在这种情况下将 src 设置回原来的样子。诀窍是记住原始 src 是什么; data 函数——它可以让你按键存储任意数据到一个元素上——可以帮助你做到这一点。

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

      【讨论】:

        【解决方案4】:
        $('.commentimg').click(function(){
            var replacesrc = $(this).attr("name");
            $(this).attr("src", replacesrc).toggleClass('commentimgresize');
        });
        

        【讨论】:

          【解决方案5】:

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

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

          另外,使用 url 作为名称可能不是最好的主意。

          【讨论】:

            猜你喜欢
            • 2012-11-16
            • 2011-11-19
            • 2011-08-31
            • 1970-01-01
            • 2012-07-14
            • 2017-12-13
            • 2013-12-06
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多