Home > Web Front-end > JS Tutorial > body text

JS实现文档加载完成后执行代码_javascript技巧

WBOY
Release: 2016-05-16 15:50:58
Original
1178 people have browsed it

在执行某些操作的时候,需要当文档完全加载完成之后再去执行,否则可能出现意向不到的情况,先看一段代码实例:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<title>脚本之家</title>
<style type="text/css"> 
div{ 
 width:200px; 
 height:200px; 
} 
</style> 
<script type="text/javascript"> 
document.getElementById("mytest").style.backgroundColor="#639"; 
</script> 
</head> 
<body> 
<div id="mytest"></div> 
</body> 
</html>

Copy after login

以上代码的初衷是将div的背景颜色设置为#639,但是并未达到我们预期的效果,这是因为文档加载的时候代码是顺序执行的,当执行js的设置背景颜色代码的时候,还没有加载到指定的div,所以js语句根本没有获取到对象。代码修改如下:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<title>脚本之家</title>
<style type="text/css"> 
div{ 
 width:200px; 
 height:200px; 
} 
</style> 
<script type="text/javascript"> 
window.onload=function(){ 
 document.getElementById("mytest").style.backgroundColor="#639"; 
} 
</script> 
</head> 
<body> 
<div id="mytest"></div> 
</body> 
</html>

Copy after login

以上代码实现了预期的效果,这是因为将代码放到了一个函数中,而此函数用作了window.onload事件的事件处理函数。window.onload事件触发的条件是当前文档完全加载完成,当此事件被触发之后,就会执行它的事件处理函数,这样因为所有文档都已加载了,就不存在js语句无法获得对象的情况了。

以上所述就是本文的全部内容了,希望大家能够喜欢。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!