javascript 和 div,在 div 中创建图像和段落。

标签 javascript html

我试图用 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);

JS Fiddle demo .

引用资料:

关于javascript 和 div,在 div 中创建图像和段落。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10865866/

相关文章:

html - 全屏登录

css - 阻止 Div 在 CSS 中不正确地堆叠

javascript - 如何将循环的每次迭代存储为innerHTML

JavaScript 内置字符集库

javascript - Background.js 找不到使用内容脚本注入(inject)的内容

javascript - 测试一系列项目的最佳方式

javascript - JavaScript 中包含 '||' 的这行代码有什么作用?

javascript - 搜索用 javascript 替换字符串的最高效方法

javascript - 展开/折叠将页面带到顶部

html - 使用 CSS 为段落添加双引号