如何使用 JavaScript 将数据附加到 div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5677799/
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
How to append data to div using JavaScript?
提问by Adham
I'm using AJAX to append data to div element, where I fill the div from JavaScript, how can I append new data to the div without losing the previous data found in div?
我正在使用 AJAX 将数据附加到 div 元素,在那里我从 JavaScript 填充 div,如何将新数据附加到 div 而不丢失在 div 中找到的先前数据?
回答by Naftali aka Neal
Try this:
尝试这个:
var div = document.getElementById('divID');
div.innerHTML += 'Extra stuff';
回答by Chandu
Using appendChild:
使用 appendChild:
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
var content = document.createTextNode("<YOUR_CONTENT>");
theDiv.appendChild(content);
Using innerHTML:
This approach will remove all the listeners to the existing elements as mentioned by @BiAiB. So use caution if you are planning to use this version.
使用innerHTML:
这种方法将删除@BiAiB 提到的现有元素的所有侦听器。因此,如果您打算使用此版本,请谨慎使用。
var theDiv = document.getElementById("<ID_OF_THE_DIV>");
theDiv.innerHTML += "<YOUR_CONTENT>";
回答by BiAiB
Beware of innerHTML
, you sort of losesomething when you use it:
当心innerHTML
,当你使用它时,你会失去一些东西:
theDiv.innerHTML += 'content',
Is equivalent to:
相当于:
theDiv.innerHTML = theDiv.innerHTML + 'content'
Which will destroy all nodes inside your div
and recreate new ones. All references and listeners to elements inside it will be lost.
这将破坏您内部的所有节点div
并重新创建新节点。对其中元素的所有引用和侦听器都将丢失。
If you need to keep them (when you have attached a click handler, for example), you have to append the new contents with the DOM functions(appendChild,insertAfter,insertBefore):
如果您需要保留它们(例如,当您附加了点击处理程序时),您必须使用 DOM 函数(appendChild,insertAfter,insertBefore)附加新内容:
var newNode = document.createElement('div');
newNode.innerHTML = data;
theDiv.appendChild( newNode )
回答by Milan Rakos
If you want to do it fastand don't want to lose references and listeners use: .insertAdjacentHTML();
如果您想快速完成并且不想丢失引用和侦听器,请使用:.insertAdjacentHTML();
"It does not reparse the elementit is being used on and thus it does not corrupt the existing elementsinside the element. This, and avoiding the extra step of serialization make it much fasterthan direct innerHTML manipulation."
“它不会重新解析它正在使用的元素,因此它不会破坏元素内的现有元素。这和避免额外的序列化步骤使它比直接的 innerHTML 操作快得多。”
Supported on all mainline browsers (IE6+, FF8+,All Others and Mobile): http://caniuse.com/#feat=insertadjacenthtml
支持所有主流浏览器(IE6+、FF8+、所有其他浏览器和移动设备):http: //caniuse.com/#feat=insertadjacenthtml
Example from https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
来自https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML 的示例
// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>
回答by Thomas Brasington
If you are using jQuery you can use $('#mydiv').append('html content')
and it will keep the existing content.
如果您使用的是 jQuery,则可以使用$('#mydiv').append('html content')
它,它会保留现有内容。
回答by Macfer Ann
Even this will work:
即使这样也可以:
var div = document.getElementById('divID');
div.innerHTML += 'Text to append';
回答by LGT
IE9+ (Vista+) solution, without creating new text nodes:
IE9+ (Vista+) 解决方案,无需创建新的文本节点:
var div = document.getElementById("divID");
div.textContent += data + " ";
However, this didn't quite do the trick for me since I needed a new line after each message, so my DIV turned into a styled UL with this code:
然而,这对我来说并没有完全奏效,因为我需要在每条消息后换行,所以我的 DIV 变成了带有以下代码的样式化 UL:
var li = document.createElement("li");
var text = document.createTextNode(data);
li.appendChild(text);
ul.appendChild(li);
From https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent:
来自https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent:
Differences from innerHTML
innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.
与innerHTML的区别
innerHTML 如其名称所示返回 HTML。很多时候,为了在元素中检索或写入文本,人们使用innerHTML。应该使用 textContent 代替。因为文本不会被解析为 HTML,所以它可能具有更好的性能。此外,这避免了 XSS 攻击向量。
回答by Vishnu Mishra
you can use jQuery. which make it very simple.
你可以使用jQuery。这使它非常简单。
just download the jQuery file add jQuery into your HTML
or you can user online link:
只需下载 jQuery 文件,将 jQuery 添加到您的 HTML 中,
或者您可以使用在线链接:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
and try this:
试试这个:
$("#divID").append(data);
回答by thatOneGuy
Why not just use setAttribute ?
为什么不直接使用 setAttribute ?
thisDiv.setAttribute('attrName','data you wish to append');
Then you can get this data by :
然后你可以通过以下方式获取这些数据:
thisDiv.attrName;
回答by Umbert
The following method is less general than others however it's great when you are sure that your last child node of the div is already a text node. In this way you won't create a new text node using appendData
MDN Reference AppendData
以下方法不如其他方法通用,但是当您确定 div 的最后一个子节点已经是文本节点时,它会很棒。这样你就不会使用MDN Reference AppendData创建一个新的文本节点appendData
let mydiv = document.getElementById("divId");
let lastChild = mydiv.lastChild;
if(lastChild && lastChild.nodeType === Node.TEXT_NODE ) //test if there is at least a node and the last is a text node
lastChild.appendData("YOUR TEXT CONTENT");