简体   繁体   English

根据Name属性的值更改背景颜色

[英]Changing background colour subject to the value of the Name attribute

I've been experimenting with a Codepen and I'm looking to change the background color of a span subject to the value of the HTML's Name attribute. 我一直在尝试使用Codepen,我希望将跨度的背景颜色更改为HTML的Name属性的值。

The following codepen demonstrates where I am so far: 以下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";
    }
});

What am I doing wrong? 我究竟做错了什么?

My end goal is for the JS to check the name attribute of a given <span> to determine what the background-color of that <span> should be. 我的最终目标是为JS检查name给定的属性<span>确定什么background-color是的<span>应该是。

Use document.addEventListener('DOMContentLoaded', function() {}) ( MDN ) instead of document.load() : 使用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> 

Your problem is this line 你的问题是这一行

document.load(function changeBackground() {

load or onload are no longer supported by browsers now change it handle DOMContentLoaded event (updated pen ) 浏览器不再支持loadonload现在更改它处理DOMContentLoaded事件(更新

document.addEventListener("DOMContentLoaded", function () {

Try using this for your document load listener: 尝试将此用于文档加载侦听器:

document.addEventListener("DOMContentLoaded", function(event) {
  // Do the business
});

so: 所以:

document.addEventListener("DOMContentLoaded", function(event) {  
  var communityName = document.getElementById("community");  
  if (communityName.getAttribute("Name") == "test") {
    communityName.style.backgroundColor = "red";
  }
});

You try to call load , but you're looking for onload . 你试着调用load ,但是你正在寻找onload

function changeBackground() {  
  var communityName = document.getElementById("community");  
  if (communityName.getAttribute("Name") == "test") {
    communityName.style.backgroundColor = "red";
  }
}

document.onload = changeBackground();

Note: Better than change CSS directly in JS is change CSS classname. 注意:比在JS中直接更改CSS更好的是改变CSS类名。

communityName.className += ' red';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM