更改所有< img>标记html文档中的src属性? [英] Change all <img> tag src attributes in html document?
问题描述
给出具有任意数量<img>
标签的任何html文档,并使用javascript,如何更改<img>
标签的所有src属性?
Given any html document with any number of <img>
tags, and using javascript, how can I change all the src attributes of the <img>
tags?
例如,从" http://example.com/somerandomimage.jpg更改<img>
标记中的所有src属性"改为" http://example.com/somerandomimage.jpg?foo=bar "
For example change all src attributes in <img>
tags from "http://example.com/somerandomimage.jpg" to "http://example.com/somerandomimage.jpg?foo=bar"
编辑 jQuery和其他JavaScript库都可以.不需要是普通的javascript.
EDIT jquery and other javascript libraries are ok. No need to be vanilla javascript.
推荐答案
您可以将document.querySelectorAll()
与选择器"img[src]"
或"[src]"
结合使用; String.prototype.indexOf()
; String.prototype.slice()
.
You can use document.querySelectorAll()
with selector "img[src]"
or "[src]"
; String.prototype.indexOf()
; String.prototype.slice()
.
如果尝试仅选择设置了src
属性的<img>
元素,则可以将选择器"img[src]"
替换为"[src]"
;其中"[src]"
选择document
中的所有元素,而src
属性出现在元素html
上.
If you are trying to select only <img>
elements which have a src
attribute set, you can substitute selector "img[src]"
for "[src]"
; where "[src]"
selects all elements in document
where src
attribute is present at element html
.
for (el of document.querySelectorAll("img[src]")) {
el.src = el.src.slice(0, el.src.indexOf("?") > -1
? el.src.indexOf("?") : el.src.length
) + "?foo=bar";
}
这篇关于更改所有< img>标记html文档中的src属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!