[英]Changing background colour subject to the value of the Name attribute
我一直在尝试使用Codepen,我希望将跨度的背景颜色更改为HTML的Name属性的值。
以下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>
你的问题是这一行
document.load(function changeBackground() {
浏览器不再支持load
或onload
现在更改它处理DOMContentLoaded
事件(更新笔 )
document.addEventListener("DOMContentLoaded", function () {
尝试将此用于文档加载侦听器:
document.addEventListener("DOMContentLoaded", function(event) {
// Do the business
});
所以:
document.addEventListener("DOMContentLoaded", function(event) {
var communityName = document.getElementById("community");
if (communityName.getAttribute("Name") == "test") {
communityName.style.backgroundColor = "red";
}
});
你试着调用load
,但是你正在寻找onload
。
function changeBackground() {
var communityName = document.getElementById("community");
if (communityName.getAttribute("Name") == "test") {
communityName.style.backgroundColor = "red";
}
}
document.onload = changeBackground();
注意:比在JS中直接更改CSS更好的是改变CSS类名。
communityName.className += ' red';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.