Why Is The ID class i styled on my seperate .JS pa

2019-09-14 20:57发布

问题:

So this is what i did when i used the put the JavaScript on a separate page: Why is it not working?????(And i made sure the source page name is yellow.js and i just dont know how to seperate the javascript file on here)

<!DOCTYPE html>
<html> 
<head>
<script src="yellow.js"></script>
</head>

<body>

<h1 id="box" onload="change()">NBA Legends</h1>

</body>

</html>

function change() {
var box = document.getElementById("box");
boxStyle = box.style;

boxStyle.color = 'red';
}

回答1:

window.onload = function change()
{
	
	var box = document.getElementById("box");
	var boxStyle = box.style;

	boxStyle.color = 'red';
}
<!DOCTYPE html>
<html> 
<head>
<script src="yellow.js"></script>
</head>

<body>

<h1 id="box" onload="change()">NBA Legends</h1>

</body>

</html>

Here is the difference between both

window.onload - it is called after all DOM, JS files, Images, Iframes, Extensions and others completely loaded. This is equal to $(window).load(function() {});

onload="" - It is called once DOM loaded. This is equal to $(document).ready(function() {});

It is always good to write clean code and I always prefer to use window.onload, instead of using onload event on element.



回答2:

First put your javascript code into the body.If you want to change color when the page load you can use window.onload = change() event. And your boxStyle variable is not defiend before you use it.I did some changes .

<body>
  <h1 id="box">NBA legends</h1>
  <script type="text/javascript">
   function change() {
    var box = document.getElementById("box");
    var boxStyle = box.style;
    boxStyle.color = 'red';
  }
 window.onload = change();
 </script> 
</body>