运行javascript x次,每次数组中的数字增加1

vohkndzv  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(387)

这是html,我无法直接更改dom,但只能使用js修改属性和类:

<div class="parent">
    <label class="child" for="label_1">
        <img src="/site/images/someimage.jpg">
    </label>
</div>
<div class="parent">
    <label class="child" for="label_2">
        <img src="/site/images/someotherimage.jpg">
    </label>
</div>
<div class="parent">
    <label class="child" for="label_3">
        <img src="/site/images/somedifferentimage.jpg">
    </label>
</div>

尝试使用js替换 img src ,因此src名称将与父项匹配 for attribute 价值,比如

<div class="parent">
    <label class="child" for="label_1">
        <img src="/site/images/label_1.jpg">
    </label>
</div>
<div class="parent">
    <label class="child" for="label_2">
        <img src="/site/images/label_2.jpg">
    </label>
</div>
<div class="parent">
    <label class="child" for="label_3">
        <img src="/site/images/label_3.jpg">
    </label>
</div>

我有这个:

<script>
let n = ""
let amt = document.getElementsByClassName("layout-choice-thumbnail-label").length;
for (let i = 0; i <= amt; i++) {
    n += i + ', ';
}

var attr = document.getElementsByClassName("child")[0].getAttribute("for");
var imgSrc = '../images/content/pagebuilder/' + cardId + '.jpg';
document.querySelectorAll(".child")[0].firstElementChild.setAttribute('src', imgSrc);
</script>

哪一个只对一个有效,我怎么能在每次页面加载时都更改它呢 [0] 增加1,或者当整个脚本加载时,所有图像名称都与 for attribute 从…起 <div class="parent"> ?

bpsygsoo

bpsygsoo1#

以下是已编辑的代码。:)

let amt = document.getElementsByClassName("child").length;

for (let i = 0; i < amt; i++) {

    var attr = document.getElementsByClassName("child")[i].getAttribute("for")
var imgSrc = '../images/content/pagebuilder/' + attr + '.jpg';
 document.querySelectorAll(".child")[i].firstElementChild.setAttribute('src', imgSrc); 
}
<div class="parent">
    <label class="child" for="label_1">
        <img src="/site/images/label_1.jpg">
    </label>
</div>
<div class="parent">
    <label class="child" for="label_2">
        <img src="/site/images/label_2.jpg">
    </label>
</div>
<div class="parent">
    <label class="child" for="label_3">
        <img src="/site/images/label_3.jpg">
    </label>
</div>

相关问题