document.write/writeln非IE/Opera浏览器中可能会造成元素获取不到

document.write/writeln在几年前的代码中见的比较多,多数情况下各浏览器表现一致。

<!DOCTYPE html>
<html>
<head></head>
<body>
	<script>
		document.write('<div id="wraper"></div>');
		var obj = document.getElementById('wraper');
		alert(obj);
	</script>
</body>
</html>

script标签写在body中,先write一个div,通过document.getElementById获取该元素。所有浏览器中都弹出了该div的信息框,证明这么写是支持的。

如果不小心把script写在head中呢,各个浏览器中行为将不一致,你可以测试下?


下面发现一个有趣的“Bug”

index.html

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

a.js

document.write('<script src="b.js"></script>');
document.write('<div id="wraper">pp</div>')
alert(document.getElementById('wraper'));

b.js

// b.js中可以不写任何代码

index.html,在IE/Opera中会弹出信息框显示该div元素,其它浏览器均为null。

当然,罪魁祸首就是 document.write('<script src="b.js"></script>');

b.js中没写任何代码,但它的确影响了非IE/Opera浏览器,很难理解为何不显示div而是null。

如果把该句删除,所有浏览器都显示div。

猜测可能是是a.js中第一个document.write覆盖了后面的document.write。测试后发现也不对,其它不变,把a.js改为

document.write('<p>hello</p>');
document.write('<div id="wraper"></div>')
alert(document.getElementById('wraper'));


这次write输出div[id=wraper]前也有一个write,但write的是p元素而非script元素,所有浏览器中表现一致都弹出div显示框而非null。


慎用document.write/writeln!

原文地址:https://www.cnblogs.com/snandy/p/1985603.html