使用Jquery追加到所有href和src属性



我需要将github存储库的名称附加到所有href和src属性的开头。感谢您的帮助。

<script>
$(document).ready(function() {
$(src).attr('src', '/Demo_App').each();
$(href).attr('href', '/Demo_App').each();
});
</script>
  1. 使用
document.getElementsByTagName('*')
  1. 循环浏览它们。如果有src,则使用前面的repo名称更新src。如果是href,则执行相同的操作,但使用href

const repoName = '/Demo_App';
window.addEventListener('load', () => {
const all = document.getElementsByTagName('*');
for (const node of all) {
const src = node.getAttribute('src');
const href = node.getAttribute('href');
if (src) node.setAttribute('src', `${repoName}${src}`);
if (href) node.setAttribute('href', `${repoName}${href}`);
}
});
<body>
<a href="https://google.com"></a>
<img src="https://google.com" />
<a href="https://google.com"></a>
<img src="https://google.com" />
<a href="https://google.com"></a>
<img src="https://google.com" />
<a href="https://google.com"></a>
<img src="https://google.com" />
</body>

使用jQuery的attr((和回调函数来附加值。

例如

const suffix = "/Demo_App";
// all elements with `src` attribute
$("[src]").attr("src", (_, src) => src + suffix)
// all elements with `href` attribute
$("[href]").attr("href", (_, href) => href + suffix)

一如既往,您可能不需要jQuery

const suffix = "/Demo_App";
document.querySelectorAll("[src]").forEach(elt => {
elt.src += suffix
})
document.querySelectorAll("[href]").forEach(elt => {
elt.href += suffix
})

最新更新