`

不要依靠if(document.all)来判断页面加载完毕

 
阅读更多


<html>
  <head>
    <title>MyHtml.html</title>
   
<script type="text/javascript">

	if(document.all){
		alert(document.getElementById("div1"));
		alert(document.getElementsByName("btn1"));
		
	}


</script>
  </head>
  
  <body>
 		
 		<div id="div1">1234</div>
 		<button name="btn1"></button>
  </body>
</html>




从这个例子可以得知,document.all这个条件不能根据id获取dom元素,但可以根据name获取到。
这样写可以避免这一状况
<script>
	if (document.all) {

		window.attachEvent('onload', show);

	}
	function show() {

		alert(document.getElementById("div1"));
	}
</script>



但是这样写的意义又何在呢?为什么不直接这样写呢?
window.onload=function () {
		alert(document.getElementById("div1"));
		alert(document.getElementsByName("btn1"));
	};

个人建议:如果要判断dom加载完毕,老老实实地使用上面这个方法。
终上所述,document.all是个bug
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics