gpt4 book ai didi

javascript - innerhtml 字符串到多个元素

转载 作者:行者123 更新时间:2023-11-28 17:26:07 26 4
gpt4 key购买 nike

是否可以像这样将 html 插入到类中?它不起作用,我在控制台中没有错误。

<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>
<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>
<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>

<script>
var currentYear = new Date().getFullYear();
var yearTarget = document.getElementsByClassName("yearTarget");
yearTarget.innerHTML = currentYear;
</script>

最佳答案

Document.getElementsByClassName()返回一个类似数组的对象。您必须指定索引或遍历所有元素才能单独设置 innerHTML:

var currentYear = new Date().getFullYear();
var yearTarget = document.getElementsByClassName("yearTarget");
[...yearTarget].forEach(function(el){
el.innerHTML = currentYear;
});
<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>
<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>
<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>

关于javascript - innerhtml 字符串到多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51570794/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com