JavaScript 动态创建 div
我试图创建函数来创建 div
并为其设置样式,代码如下: http://jsfiddle.net/NGnEd/5/。
<script type="text/javascript">
var dom = {
// Build the main button
buildButton: function(){
// Create new DOM element - div
var button = document.createElement('div');
// Set element attribute
button.setAttribute('id', 'newElement');
// Style the element
button.style.width = "100px";
button.style.height = "100px";
// Add content
button.innerHTML = 'new Element';
// Print element
document.body.innerHTML += button;
}
}
</script>
<div onclick="dom.buildButton();">
The first div
</div>
它应该创建元素、设计元素、添加内容并打印它。但它不起作用,我不知道原因。
有什么帮助吗?
I was trying to create function to create a div
and style it, here is the code: http://jsfiddle.net/NGnEd/5/.
<script type="text/javascript">
var dom = {
// Build the main button
buildButton: function(){
// Create new DOM element - div
var button = document.createElement('div');
// Set element attribute
button.setAttribute('id', 'newElement');
// Style the element
button.style.width = "100px";
button.style.height = "100px";
// Add content
button.innerHTML = 'new Element';
// Print element
document.body.innerHTML += button;
}
}
</script>
<div onclick="dom.buildButton();">
The first div
</div>
It is supposed to create element, style it, add content and print it. But it's not working, I don't know the reason.
Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法将 HTML 元素添加到字符串中。 正如 @Felix Kling 所指出的,您没有正确设置 JSFiddle,而是
错误地设置了“Try
Also”,因此
onclick="dom.buildButton"
不起作用。此处的工作示例:http://jsfiddle.net/pnHRp/1/
You can't add an HTML element to a string. Instead of
Try
Also, as noted by @Felix Kling, you set up the JSFiddle incorrectly, so
onclick="dom.buildButton"
does not work. Working example here:http://jsfiddle.net/pnHRp/1/