简体   繁体   English

Dom 解析和 javascript 执行

[英]Dom parsing and javascript execution

<script src="mmm.js"></script>
<style>
 #box{
    width:150px;
    height:150px;
    background-color:red;
 }
</style>
</head>
<body>
  <div id="box"></div>
</body>

and the mmm.js file和 mmm.js 文件

$('#box').css("background-color","black");

Why the above code works?为什么上面的代码有效? The following code does not work:以下代码不起作用:

<script>
  $('#box').css("background-color","black");
</script>
<div id="box"></div>

and this is rational since box is not known to the script.这是合理的,因为脚本不知道box How box is known to the external script since it is placed above body and is executed before <div id="box"></div> is parsed?由于box位于body上方并在解析<div id="box"></div>之前执行,因此外部脚本如何知道它?

I tried your code and it doesn't work either way to me.我试过你的代码,但它对我不起作用。 Either way the box does not change background.无论哪种方式,框都不会改变背景。

What you ought to do is make sure the page has been fully loaded before switching the background to black:您应该做的是在将背景切换为黑色之前确保页面已完全加载:

$( document ).ready(function() {
     $('#box').css("background-color","black");
});

You can place this in a .js file or inside your HTML.您可以将其放在 .js 文件或 HTML 中。

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

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