使用 JavaScript 在 div 中添加/删除 HTML

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

Add/remove HTML inside div using JavaScript

javascripthtmlinnerhtml

提问by Daniel Tovesson

I want to be able to add multiple rows to a div and also removing them. I have a '+' button at the top of the page which is for adding content. Then to the right of every row there is a '-' button that's for removing that very row. I just can't figure out the javascript code in this example.

我希望能够将多行添加到 div 并删除它们。我在页面顶部有一个“+”按钮,用于添加内容。然后在每一行的右侧有一个“-”按钮,用于删除该行。我就是想不通这个例子中的 javascript 代码。

This is my basic HTML structure:

这是我的基本 HTML 结构:

<input type="button" value="+" onclick="addRow()">

<div id="content">

</div>

This is what I want to add inside the content div:

这是我想在内容 div 中添加的内容:

<input type="text" name="name" value="" />
<input type="text" name="value" value="" />
<label><input type="checkbox" name="check" value="1" />Checked?</label>
<input type="button" value="-" onclick="removeRow()">

回答by Austin Brunkhorst

You can do something like this.

你可以做这样的事情。

function addRow() {
  const div = document.createElement('div');

  div.className = 'row';

  div.innerHTML = `
    <input type="text" name="name" value="" />
    <input type="text" name="value" value="" />
    <label> 
      <input type="checkbox" name="check" value="1" /> Checked? 
    </label>
    <input type="button" value="-" onclick="removeRow(this)" />
  `;

  document.getElementById('content').appendChild(div);
}

function removeRow(input) {
  document.getElementById('content').removeChild(input.parentNode);
}

回答by Hoffmann

To my most biggest surprise I present to you a DOM method I've never used before googeling this question and finding ancient insertAdjacentHTMLon MDN(see CanIUse?insertAdjacentHTMLfor a pretty green compatibility table).

最令我惊讶的是,我向您展示了一个我从未使用过的 DOM 方法,之前我在谷歌搜索这个问题并insertAdjacentHTMLMDN上找到了古老的方法(请参阅CanIUse?insertAdjacentHTML以获得一个非常绿色的兼容性表)。

So using it you would write

所以使用它你会写

function addRow () {
  document.querySelector('#content').insertAdjacentHTML(
    'afterbegin',
    `<div class="row">
      <input type="text" name="name" value="" />
      <input type="text" name="value" value="" />
      <label><input type="checkbox" name="check" value="1" />Checked?</label>
      <input type="button" value="-" onclick="removeRow(this)">
    </div>`      
  )
}

function removeRow (input) {
  input.parentNode.remove()
}
<input type="button" value="+" onclick="addRow()">

<div id="content">
</div>

回答by Arun

You can use this function to add an child to a DOM element.

您可以使用此函数向 DOM 元素添加子元素。

function addElement(parentId, elementTag, elementId, html) 

 {


// Adds an element to the document


    var p = document.getElementById(parentId);
    var newElement = document.createElement(elementTag);
    newElement.setAttribute('id', elementId);
    newElement.innerHTML = html;
    p.appendChild(newElement);
}



function removeElement(elementId) 

{

    // Removes an element from the document
    var element = document.getElementById(elementId);
    element.parentNode.removeChild(element);
}

回答by Arun

To remove node you can try this solution it helped me.

要删除节点,您可以尝试此解决方案,它对我有帮助。

var rslt = (nodee=document.getElementById(id)).parentNode.removeChild(nodee);

回答by Catalin Matei

Another solution is to use getDocumentByIdand insertAdjacentHTML.

另一种解决方案是使用getDocumentByIdinsertAdjacentHTML

Code:

代码:

function addRow() {

 const  div = document.getElementById('content');

 div.insertAdjacentHTML('afterbegin', 'PUT_HTML_HERE');

}

Check here, for more details: Element.insertAdjacentHTML()

在这里查看更多详细信息: Element.insertAdjacentHTML()

回答by Aarif Qureshi

please try following to generate

请尝试以下生成

 function addRow()
    {
        var e1 = document.createElement("input");
        e1.type = "text";
        e1.name = "name1";

        var cont = document.getElementById("content")
        cont.appendChild(e1);

    }

回答by dashme

make a class for that button lets say :

为该按钮创建一个类让我们说:

`<input type="button" value="+" class="b1" onclick="addRow()">`

your js should look like this :

你的 js 应该是这样的:

$(document).ready(function(){
  $('.b1').click(function(){
      $('div').append('<input type="text"..etc ');
  });
});

回答by Aezaz Desai

<!DOCTYPE html>
<html>
<head>
    <title>Dynamical Add/Remove Text Box</title>
    <script language="javascript">

        localStorage.i = Number(1);

        function myevent(action)
        {
            var i = Number(localStorage.i);
            var div = document.createElement('div');

            if(action.id == "add")
            {
                localStorage.i = Number(localStorage.i) + Number(1);
                var id = i;
                div.id = id;
                div.innerHTML = 'TextBox_'+id+': <input type="text" name="tbox_'+id+'"/>' + ' <input type="button" id='+id+' onclick="myevent(this)" value="Delete" />';

                document.getElementById('AddDel').appendChild(div);
            }
            else
            {
                var element = document.getElementById(action.id);
                element.parentNode.removeChild(element);
            }
        }
    </script>
</head>
<body>
    <fieldset>
    <legend>Dynamical Add / Remove Text Box</legend>
    <form>
        <div id="AddDel">
            Default TextBox:
            <input type="text" name="default_tb">
            <input type="button" id="add" onclick="myevent(this)" value="Add" />
        </div>
            <input type="button" type="submit" value="Submit Data" />
    </form>
    </fieldset>
</body>
</html>