如何在 JavaScript 中以各种可能的方式动态创建新 div、更改它、移动它、修改它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14094697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:42:44  来源:igfitidea点击:

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

javascriptdom

提问by Erik Nelson

I want to create new divs as the page loads. These divs will appear as an ordered group which changes depending upon external data from a JSON file. I will need to do this with a for loop because there are over 100 divs needed.

我想在页面加载时创建新的 div。这些 div 将显示为一个有序组,该组根据来自 JSON 文件的外部数据而变化。我将需要使用 for 循环来执行此操作,因为需要 100 多个 div。

So, I need to be able to change each created div in regards to height, width, top/left and so on. Yet, document.getElementById("created_div").style.whateverdoes nothing, I can't even see a single new div appear. I've set the new divs height/width to 500px, background to "red", and so on, but no new divs are definitely appearing.

所以,我需要能够在高度、宽度、顶部/左侧等方面更改每个创建的 div。然而,document.getElementById("created_div").style.whatever什么都不做,我什至看不到一个新的 div 出现。我已将新 div 的高度/宽度设置为 500 像素,将背景设置为“红色”,等等,但肯定没有出现新的 div。

What am I doing wrong?

我究竟做错了什么?

回答by Ryan Stein

This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.

这涵盖了 DOM 操作的基础知识。请记住,要使新创建的节点在文档中可见,需要将元素添加到正文或包含正文的节点。

回答by Brad Ross

Have you tried JQuery? Vanilla javascript can be tough. Try using this:

你试过JQuery吗?香草 javascript 可能很难。尝试使用这个:

$('.container-element').add('<div>Insert Div Content</div>');

.container-elementis a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add()function inserts HTML into the container-element.

.container-element是一个 JQuery 选择器,它用类“container-element”(大概是您要插入 div 的父元素)标记元素。然后该add()函数将 HTML 插入到容器元素中。