Py学习  »  Jquery

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

jmurph91 • 3 年前 • 1391 次点击  

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

<script>
  $(document).ready(function() {
    $(src).attr('src', '/Demo_App').each();
    $(href).attr('href', '/Demo_App').each();
});
</script>
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130153
 
1391 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Phil
Reply   •   1 楼
Phil    3 年前

使用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)

一如既往 you might not need jQuery

const suffix = "/Demo_App";

document.querySelectorAll("[src]").forEach(elt => {
  elt.src += suffix
})

document.querySelectorAll("[href]").forEach(elt => {
  elt.href += suffix
})
mstephen19
Reply   •   2 楼
mstephen19    3 年前
  1. 使用以下命令选择DOM上的所有节点:
document.getElementsByTagName('*')
  1. 在它们之间循环。如果有src,则在src前面更新repo名称。如果是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>