javascript 使用相同的类javascript创建多个div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20308270/
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-10-27 18:12:20  来源:igfitidea点击:

create multiple divs with the same class javascript

javascript

提问by Yamaha32088

I am new to JavaScript and would like to know how I can create multiple divs dynamically with the same class name. I have the following code but it only creates one instance of the div.

我是 JavaScript 的新手,想知道如何使用相同的类名动态创建多个 div。我有以下代码,但它只创建了一个 div 实例。

<div id="wrapper">
    <div id="container">
        <div id="board">
            <script>
                var board = document.createElement('div');
                board.className = "blah";

                for(x=0; x<9;x++) {
                document.getElementById('board').appendChild(board);
                }
            </script>
        </div>
    </div>
</div>

采纳答案by Thomas Kelley

Right now, you're creating the element outsidethe loop, and appending thatelement to the DOM...again and again.

现在,您正在循环创建元素,并将元素附加到 DOM 中……一次又一次。

What you want to do is create a new element during every iteration of the loop. To do that, move the part where you create the new div inside the loop:

您想要做的是在循环的每次迭代期间创建一个新元素。为此,请移动您在循环内创建新 div 的部分:

for(x=0; x<9;x++) {
    var board = document.createElement('div');
    board.className = "blah";

    document.getElementById('board').appendChild(board);
}

Now, every time the loop runs, you'll create a new element, and append that element to the element with ID #board.

现在,每次循环运行时,您将创建一个新元素,并将该元素附加到具有 ID 的元素#board

It's worth pointing out that the variable you created (board) now only has scope within this loop. That means that once the loop is done, you'll need to find a different way to access the new elements, if you need to modify them.

值得指出的是,您创建的变量 ( board) 现在仅在此循环内具有作用域。这意味着一旦循环完成,您将需要找到一种不同的方式来访问新元素,如果您需要修改它们。

回答by NenadP

Others did answer the question in a nutshell; here is one approach which addresses some issues that are present in the your and proposed code snippets, and maybe gives your some insight for further exploration. I hope it helps :)

其他人确实简单地回答了这个问题;这是一种解决您和建议的代码片段中存在的一些问题的方法,并且可能为您提供一些进一步探索的见解。我希望它有帮助:)

To extend a script a little bit, this solution creates every element by using function createDiv, and references to individual divs are stored in an array, so you can modify the content of each div by modifying array elements, which are referring to DOM elements. (in this example, I modify 6th div for demonstration sake)

为了稍微扩展一个脚本,这个解决方案使用函数createDiv创建每个元素,并且对单个div的引用存储在一个数组中,因此您可以通过修改数组元素来修改每个div的内容,这些元素引用DOM元素。(在这个例子中,为了演示,我修改了第 6 个 div)

Notes:

笔记:

  • All of your code is thrown in a global object, it's good practice to encapsulate your code, here in immediately invoked anonymous function.
  • x would be thrown in a global object even if encapsulated, you need always to declare your variables with a var keyword. Here I declare all vars needed upfront in one statement, which is also a good practice;
  • It is convention to use "i" for loop iterator variable.
  • Avoid "magic numbers" (9), rather create a variable that will describe what you do in your code. It is good if the code describes what it does.
  • Also in this example, we avoid declaring "board" on each loop iteration (the element where your divs get appended.)
  • Test your code in JSLint- great tool to validate your scripts. (this will pass the test, given that you set indentation to 2.
  • "use strict" - read here.
  • 您的所有代码都被抛出到一个全局对象中,将您的代码封装在此处是立即调用的匿名函数的好习惯。
  • 即使封装 x 也会被抛出到全局对象中,您需要始终使用 var 关键字声明变量。在这里,我在一个语句中预先声明了所有需要的变量,这也是一种很好的做法;
  • 循环迭代器变量使用“i”是惯例。
  • 避免使用“魔法数字” (9),而是创建一个变量来描述您在代码中的操作。如果代码描述了它的作用,那就太好了。
  • 同样在这个例子中,我们避免在每次循环迭代中声明“board”(附加 div 的元素。)
  • JSLint 中测试您的代码- 验证您的脚本的好工具。(这将通过测试,因为您将缩进设置为 2。
  • “使用严格” -在这里阅读

/*jslint browser:true */

(function () {
  "use strict";

  function createDiv() {
    var boardDiv = document.createElement("div");

    boardDiv.className = "new-div";
    boardDiv.innerText = "I am new DIV";

    return boardDiv;
  }

  function createAndModifyDivs() {
    var board = document.getElementById("board"),
      myDivs = [],
      i = 0,
      numOfDivs = 9;

    for (i; i < numOfDivs; i += 1) {
      myDivs.push(createDiv());
      board.appendChild(myDivs[i]);
    }

    myDivs[5].className = "modified-div";
    myDivs[5].innerText = "I'm modified DIV";
  }

  createAndModifyDivs();

}());
.new-div {
color: gray;  
}

.modified-div {
color: red;  
}
<!DOCTYPE html>
<html>
  <head>
    <title>Inserting Divs</title>
  </head>
  <body>
    <div id="wrapper">
      <div id="container">
        <div id="board">
        </div>
      </div>
    </div>
  </body>
</html>

回答by Tom Chung

Only a single element is created.

只创建一个元素。

        <script>
            var board = document.createElement('div');
            board.className = "blah";

            for(x=0; x<9;x++) {
            document.getElementById('board').appendChild(board);
            }
        </script>

Should be written as:

应该写成:

        <script>
            for(x=0; x<9;x++) {
            var board = document.createElement('div');
            board.className = "blah";
            document.getElementById('board').appendChild(board);
            }
        </script>