我一直在尝试使用 Codepen,我希望根据 HTML 的名称属性的值更改范围的背景颜色。
以下codepen展示我到目前为止的位置:
<div class="card-body">
<span id="community" class="card-community-tag" Name="test">Community 1</span>
<span class="card-community-tag">Community 2</span>
</div>
document.load(function changeBackground() {
var communityName = document.getElementById("community");
if (communityName.getAttribute("Name") == "test") {
communityName.style.backgroundColor = "red";
}
});
我做错了什么?
我的最终目标是让 JS 检查 name
给定 <span>
的属性确定 background-color
是什么其中<span>
应该是。
最佳答案
使用 document.addEventListener('DOMContentLoaded', function() {})
( MDN ) 代替 document.load()
:
document.addEventListener('DOMContentLoaded', function() {
var communityName = document.getElementById("community");
if (communityName.getAttribute("Name") == "test") {
communityName.style.backgroundColor = "red";
}
});
<div class="card-body">
<span id="community" class="card-community-tag" Name="test">Community 1</span>
<span class="card-community-tag">Community 2</span>
</div>
关于javascript - 根据 Name 属性的值更改背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47306999/