我尝试使用javascript创建div
标记。?但为什么它不起作用?
我见过document.createElement not working
Javascript createElement() not working in Chrome 但这些答案不适合我的剧本。
<html>
<head>
<script>
var div = '<div id = con style="width:auto; height:200px; Background:#2a2a2a">';
var x = document.createElement(div);
var y = document.getElementById('con');
y.innerHTML = "hello world";
document.body.appendChild(x);
</script>
</head>
<body>
</body>
</html>
我该怎么做?
答案 0 :(得分:4)
它不能这样工作。 .createElement()
仅排除您要创建的元素的类型,不包含预定义的HTML代码段。因此,您必须使用document.createElement('div');
创建 Div 元素,然后再处理该元素。像
For Instance
var div = document.createElement('div');
div.id = 'con';
div.style.cssText = "width:auto; height:200px; Background:#2a2a2a";
document.body.appendChild( div );
如果您不需要对元素的引用,并且您只想插入新的HTML代码,那么您也可以使用Element.prototype.insertAdjacentHTML()
,如此
document.body.insertAdjacentHTML( 'beforeend', '<div id="con" style="width:auto; height:200px; Background:#2a2a2a">');
此处代码的另一个问题是您尝试过早访问DOM。即使代码 以当前形式工作,您也无法访问document.body
部分中的<head>
,因为此时尚未完全初始化。将整个<script>
来源移至<body>
部分,或将聆听者附加到DOMContentLoaded
事件。
答案 1 :(得分:1)
你不能像这样创建一个预定义的html,因为你要附加到body,脚本应该在body元素里面而不是在头部
<html>
<head>
</head>
<body>
<script>
var x = document.createElement('div');
x.id = 'con';
x.style.width = 'auto';
x.style.height = '200px';
x.style.background = '#2a2a2a';
x.innerHTML = "hello world";
document.body.appendChild(x);
//no need to access `y` by id, use the reference returned by createElement to set the content
//var y = document.getElementById('con');
//y.innerHTML = "hello world";
</script>
</body>
</html>
答案 2 :(得分:1)
如果您想一次性插入整个HTML结构,您可以使用非常有用的,跨浏览器且不公平的鲜为人知的insertAdjacentHTML
方法:
var div = '<div id="con" style="width:auto; height:200px; Background:#2a2a2a"></div>';
document.body.insertAdjacentHTML('beforeend', div);
var y = document.getElementById('con');
y.innerHTML = "hello world";