Js 30 BOM
小知识点,
1.document.write()方法:
如果document.write()在一个事件中或window.onload=function(){}这个function里,
那么document.write()会做两件事:先清空html内容,然后再写入write()里的代码。
2.关于document.getElementById('xxx');的用法,如果document.getElementById('xxx')写在function外面
就获取不到任何数据,即返回值为null。具体例子如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script> var oTxt = document.getElementById('txt1'); // null, var oBtn = document.getElementById('btn1'); // null, alert('=======:'+oBtn); window.onload = function(){ alert('oBtn:'+oBtn); oBtn.onclick = function(){ //理所当然的,oBtn.onclick也就无从说起。 //window.open('about:blank'); alert('--=======999'); window.open('http://www.baidu.com/'); } } </script> </head> <body> <input type="button" id="btn1" value="dianwo"/> <textarea id="txt1" ></textarea></br> </body> </html>
具体的解决办法如下,即把document.getElementById('xxx');写在function()里面,具体如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script> window.onload = function(){ var oTxt = document.getElementById('txt1'); //这样就可以获取到值了,oTxt不像上面一样为null了 var oBtn = document.getElementById('btn1'); alert('=======:'+oBtn); oBtn.onclick = function(){ //window.open('about:blank'); alert('--=======999'); window.open('http://www.baidu.com/'); } } </script> </head> <body> <input type="button" id="btn1" value="dianwo"/> <textarea id="txt1" ></textarea></br> </body> </html>