【问题标题】:How to change inner html of an <img> tag?如何更改 <img> 标签的内部 html?
【发布时间】:2016-08-29 08:00:10
【问题描述】:
正在输出:
<img width="1080" height="1080" src="/image.jpg" class="post-image" alt="image" />
我需要把它改成这样:(src → data)
<img width="1080" height="1080" data="/image.jpg" class="post-image" alt="image" />
【问题讨论】:
标签:
jquery
html
image
attr
【解决方案1】:
只需使用下面的简单 JQ :
首先获取src,然后将其添加为data,然后删除src
var src = $("img").attr("src")
$("img").attr("data", src).removeAttr("src")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img width="1080" height="1080" src="/image.jpg" class="post-image" alt="image" />
【解决方案2】:
您可以使用 jQuery 的attr 和removeAttr 来添加get、set 和remove 属性。
var img = $("img");
img.attr("data", img.attr("src")).removeAttr("src");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img width="1080" height="1080" src="/image.jpg" class="post-image" alt="image" />