日期:2014-05-19  浏览次数:20445 次

请教,通过外部js文件方式写的元素如何去访问?
比如在一个静态页面中以
<script   id= "myjs "   type= "text/javascript "   src= "myjs.js "> </script> 的方式引入。在myjs.js我生成了一个DIV,ID是divid,如何去访问这个DIV?
我用document.getElementById( "divid ")的话会提示找不到对象。

------解决方案--------------------
可以直接调用的,
确定 <script id= "myjs " type= "text/javascript " src= "myjs.js "> </script> 的代码执行过
,即在使用document.getElementById( "divid ")前执行完上。
------解决方案--------------------
你是如何 生成的 ?
要如下那样才可以var alertFram = document.createElement( "DIV ");

var alertFram = document.createElement( "DIV ");
alertFram.id= "alertFram ";
alertFram.style.position = "absolute ";
alertFram.style.left = "50% ";
alertFram.style.top = "50% ";
alertFram.style.marginLeft = "-225px " ;
alertFram.style.marginTop = -75+document.documentElement.scrollTop+ "px ";
alertFram.style.width = "450px ";
alertFram.style.height = "150px ";
alertFram.style.background = "#ccc ";
alertFram.style.textAlign = "center ";
alertFram.style.lineHeight = "150px ";
alertFram.style.zIndex = "10001 ";
------解决方案--------------------
在JS里这样也可以
document.write( ' <div id= "test " class= "test "> </div> ');
------解决方案--------------------
你将JS文件里的代码全部复制到你的当前页试试
------解决方案--------------------
没问题的,请注意以下几点:
一、用js生成div,注意该js在body区调用

二、document.getElementById( "xxx ")时xxx要已生成。


我测试的代码如下:
.html
<!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=gb2312 " />
<title> 无标题文档 </title>
<script language= "javascript ">
function z()
{
document.getElementById( "abc ").innerHTML = "OK ";
}
</script>
</head>
<body>
<script src= "a.js "> </script>
<script language= "javascript ">
z();
</script>
</body>
</html>


.js
<!--
document.write( " <div id= 'abc '> </div> ");
-->