我试图用 javascript 做一些基本的事情,让它自动生成一些网站内容,但这让我发疯了!!!有人可以告诉我一个简单的例子,说明如何让 javascript 在 div 中创建新图像和段落。假设我的网站结构是这样的......
<html>
<head>
</head>
<body>
<div id ="wrapper">
<div id ="content">
</div>
</div>
</body>
</html
我将如何使用 javascript 函数在“内容”div 中创建图像和段落加载页面以及单击图像。我知道它必须与 DOM 相关,但我已经这样做了几个小时,但我无法让它工作!请告诉我它是如何完成的一个例子。非常感谢!!!!
最佳答案
最简单的形式:
// gets a reference to the div of id="content":
var div = document.getElementById('content'),
// creates a new img element:
img = document.createElement('img'),
// creates a new p element:
p = document.createElement('p'),
// creates a new text-node:
text = document.createTextNode('some text in the newly created text-node.');
// sets the src attribute of the newly-created image element:
img.src = 'http://lorempixel.com/400/200/people';
// appends the text-node to the newly-created p element:
p.appendChild(text);
// appends the newly-created image to the div (that we found above):
div.appendChild(img);
// appends the newly-created p element to the same div:
div.appendChild(p);
引用资料:
关于javascript 和 div,在 div 中创建图像和段落。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10865866/