在 HTML javascript 中动态附加 Div

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

Dynamically append Div in HTML javascript

jqueryhtmljavascript-eventsjavascript

提问by MKD

I have created a div in HTML and want to add inner div dynamically to it. Below is the code for HTML.

我已经在 HTML 中创建了一个 div,并希望向它动态添加内部 div。下面是 HTML 的代码。

<div id="table">
    <div class="row">
        This is the Demo First row Content.
        <div class="cell1">
            Cell 1 Content
        </div>
        <div class="cell2">
            Cell 2 Content
        </div>
    </div>
    <div class="row">
        This is the Demo Second row Content.
        <div class="cell1">
            Cell 1 Content
        </div>
        <div class="cell2">
            Cell 2 Content
        </div>
    </div>
</div>

<input type="button" value="Add New Row" onclick="addNewRow()"  />

My Css is

我的 CSS 是

div {
       border: 1px dotted red;
       padding: 10px;    
    }

And I have done the javaScript for it but it is not working. The javaScript is

我已经为它完成了 javaScript 但它不起作用。javaScript 是

function addNewRow {
    var table = document.getElementById('table');

    var rDiv = document.createElement('div');

    table.appendChild(rDiv);

    rDiv.innerHTML = "This is the Demo Third row Content.";

    var c1Div = document.createElement('div');
    rDiv.appendChild(c1Div);
    c1Div.innerHTML = "Cell 1 Content";

    var c2Div = document.createElement('div');
    rDiv.appendChild(c2Div);
    c2Div.innerHTML = "Cell 2 Content";
}

But when I executed it. The new rows are not added. Please guide me what I am missing.

但是当我执行它时。不会添加新行。请指导我我所缺少的。

Regards,
Dinesh

问候,
迪内什

回答by Tibos

You have a typo preventing the execution of the function. The correct name is document.getElementById(line 2 in JS).

你有一个错字阻止了函数的执行。正确的名称是document.getElementById(JS 中的第 2 行)。

You might want to enable the console (F12 IE debugger, Firebug, Developer Tools, etc) for debugging next time. These kinds of errors are very easy to spot.

您可能希望在下次调试时启用控制台(F12 IE 调试器、Firebug、开发人员工具等)。这些类型的错误很容易被发现。

Here is a working JsBin: http://jsbin.com/egImArO/1/edit

这是一个有效的 JsBin:http://jsbin.com/egImArO/1/edit

回答by Maulik patel

define javascript function like function addNewRow() {not a function addNewRow {

定义 javascript 函数,如function addNewRow() {不是函数 addNewRow {

回答by itzmukeshy

Just replace first js code line with this one:-

只需用这个替换第一行 js 代码行:-

function addNewRow(){

函数 addNewRow(){