像下面的例子js插入一张图片 是根据文档的顺序 怎么才能改变JS插入代码的位置
比如我想写入一段代码到<html>上面或是<head>里面 该怎么做
<!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>
</head>
<body>
<div style="width:100px;height:100px;background:red;"></div>
<script type="text/javascript">
document.write("<img src='http://www.baidu.com/img/baidu_logo.gif'");
</script>
</body>
</html>
比如我想写入一段代码到<html>上面或是<head>里面 该怎么做
<!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>
</head>
<body>
<div style="width:100px;height:100px;background:red;"></div>
<script type="text/javascript">
document.write("<img src='http://www.baidu.com/img/baidu_logo.gif'");
</script>
</body>
</html>
<div id='t'></div>
<script>document.getElementById('t').innerHTML = 'aaaa'</script>
或者用JS创建一个容器,插入HTML代码。然后再把这个容器放到你指定的位置。
<div id='t'></div>
<script>
var s = document.createElement('div');
s.innerHTML = 'aaaa'
var p = document.getElementById('t');
document.insertBefor(s, p) //p前面
document.insertBefor(s, p.nextSibling) //p后面
</script>