Javascript HTML:使用 JS 动态添加元素

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

HTML: Add elements dynamically using JS

javascripthtml

提问by Emilio Zaidman

Working with HTML5, I have created a simple table that consists of a series of pair fields (Activity log, time). I've been searching on the web how to dynamically create fields using Javascript, but I've only found how to create one field at a time (using getElementById). The thing is that I'd like to create a series of tags. Meaning, when the user clicks on "add another field", I'd like that JS generates another row on the table, with a pair of fields, instead of having to hard code the complete table (the snippet below only has two rows, but I'd probably need 10-15 rows).

使用 HTML5,我创建了一个简单的表格,其中包含一系列对字段(活动日志、时间)。我一直在网上搜索如何使用 Javascript 动态创建字段,但我只找到了如何一次创建一个字段(使用 getElementById)。问题是我想创建一系列标签。意思是,当用户点击“添加另一个字段”时,我希望 JS 在表格上生成另一行,其中包含一对字段,而不必对整个表格进行硬编码(下面的代码片段只有两行,但我可能需要 10-15 行)。

The snippet of the code for the table appears below. Using CSS the page looks as it's on the screen shot. screenshot:

该表的代码片段如下所示。使用 CSS 页面看起来就像它在屏幕截图上一样。 截图

I'd appreciate any help. Thanks in advance.

我很感激任何帮助。提前致谢。

<!DOCTYPE html>
<html>
<head lang="en">
   <meta charset="utf-8">
   <title>Activity Log</title>
   <link href="styles.css" rel="stylesheet">
   <script type="text/javascript" language="javascript" src="script.js"></script>

</head>

<body>
<div class="container">
    <div class="row">
        <div class="leftcol">
            <form name='mainForm' id='mainForm' method="get" action="http://www.randyconnolly.com/tests/process.php">
  <fieldset>
     <legend>Input Activity Logs</legend>
     <table id=tracklist>
      <tr>
        <th colspan="3">Track List: </th>
      </tr>
      <tr>
        <td>1</td>
        <td><label>Activity Log: </label><br/><input type="text" name="actlog1" class="required"></td>
        <td><label>Time: </label><br/><input type="time" name="time1" class="required"></td>
      </tr>
      <tr>
        <td>2</td>
        <td><label>Activity Log: </label><br/><input type="text" name="actlog2" class="required"></td>
        <td><label>Time: </label><br/><input type="time" name="time2" class="required"></td>
      </tr>
     </table>
     <input type="submit" />
  </fieldset>
</form>
        </div>

    </div>
</div>
</body>
</html>

采纳答案by samcervantes

You can use the .innerHTML += method wired up to an "Add Activity" button. Each time you click the button a new table row is added with the correct index numbers. Here is a fully working example - for the sake of simplicity and having only one file, I've included the javascript directly in the HTML code:

您可以使用连接到“添加活动”按钮的 .innerHTML += 方法。每次单击该按钮时,都会添加一个带有正确索引号的新表格行。这是一个完整的示例 - 为简单起见并且只有一个文件,我将 javascript 直接包含在 HTML 代码中:

<!DOCTYPE html>
<html>
<head lang="en">
   <meta charset="utf-8">
   <title>Activity Log</title>
   <script>

      // Wait until the window finishes loaded before executing any script
      window.onload = function() {

        // Initialize the activityNumber
        var activityNumber = 3;

        // Select the add_activity button
        var addButton = document.getElementById("add_activity");

        // Select the table element
        var tracklistTable = document.getElementById("tracklist");

        // Attach handler to the button click event
        addButton.onclick = function() {

        // Add a new row to the table using the correct activityNumber
          tracklistTable.innerHTML += '<tr><td>' + activityNumber + '</td><td><label>Activity Log: </label><br/><input type="text" name="actlog' + activityNumber + '" class="required"></td><td><label>Time: </label><br/><input type="time" name="time' + activityNumber + '" class="required"></td></tr>';

          // Increment the activityNumber
          activityNumber += 1;
        }

      }

   </script>

</head>

<body>
  <div class="container">
      <div class="row">
          <div class="leftcol">
              <form name='mainForm' id='mainForm' method="get" action="#">
                <fieldset>
                   <legend>Input Activity Logs</legend>
                   <table id="tracklist">
                    <tr>
                      <th colspan="3">Track List: </th>
                    </tr>
                    <tr>
                      <td>1</td>
                      <td><label>Activity Log: </label><br/><input type="text" name="actlog1" class="required"></td>
                      <td><label>Time: </label><br/><input type="time" name="time1" class="required"></td>
                    </tr>
                    <tr>
                      <td>2</td>
                      <td><label>Activity Log: </label><br/><input type="text" name="actlog2" class="required"></td>
                      <td><label>Time: </label><br/><input type="time" name="time2" class="required"></td>
                    </tr>
                   </table>
                   <input type="submit" />
                </fieldset>
              </form>
              <button id="add_activity">Add Activity</button>
          </div>
      </div>
  </div>
</body>
</html>

回答by Hector Barbossa

Add a button like <input type="button" onclick="cloneRow()" value="Clone Row" />in your html and add a id to the row to be copied (exm. <tr id="rowToClone">) then add the following javascript function in your code

<input type="button" onclick="cloneRow()" value="Clone Row" />在您的 html 中添加一个按钮 ,并向要复制的行添加一个 id(exm。 <tr id="rowToClone">),然后在您的代码中添加以下 javascript 函数

 function cloneRow() {
     var row = document.getElementById("rowToClone"); // find row to copy
     var table = document.getElementById("tracklist"); // find table to append to
     var clone = row.cloneNode(true); // copy children too
     clone.id = "newID"; // change id or other attributes/contents
     table.appendChild(clone); // add new row to end of table
 }

回答by L_K

Some popular ways to add element:

添加元素的一些流行方法:

  1. Use document.createElementto create element you need, and use document.appendChildor document.insertBeforeto add it to html.
  2. Use element.insertAdjacentHTMLto add element.
  3. Use libraries like jQuery and React.
  1. 使用document.createElement创建所需元素,并使用document.appendChilddocument.insertBefore将其添加到HTML。
  2. 使用element.insertAdjacentHTML添加元素。
  3. 使用 jQuery 和 React 等库。

回答by babak

Syntax is here:

语法在这里:

`<span> ${data.d.name}</span>`

回答by Richard Barker

What you need is document.createElemrnt(tagNameString);That function does exactly what you think. Then you can create more elements and make them children of another.

您需要的是document.createElemrnt(tagNameString);该功能完全符合您的想法。然后您可以创建更多元素并使它们成为另一个元素的子元素。