更改所有< img>标记html文档中的src属性? [英] Change all <img> tag src attributes in html document?

查看:142
本文介绍了更改所有< img>标记html文档中的src属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出具有任意数量<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";
}

这篇关于更改所有&lt; img&gt;标记html文档中的src属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆