[英]How can I append a <br> using document.getElementByID?
我正在尝试使用 DOM 附加一个<p>
元素来附加一个股票代码和股票价格,然后使用<br>
转到一个新行,但是当我运行这个时:
for(var i=0; i<stockPrices.length; i++){
document.getElementById("stockprice").append(stockNames[i]+" ");
document.getElementById("stockprice").append(stockPrices[i]+" ");
document.getElementById("stockprice").append("<br>");
}
它实际上将文本<br>
添加到我的“股票价格”元素中。 这样做的正确方法是什么?
使用insertAdjacentHTML
代替:
document.body.append('content'); document.body.insertAdjacentHTML('beforeend', '<br>'); document.body.append('more content');
我建议不要与现有的innerHTML
连接,因为那样会
(1) 破坏容器内现有的侦听器(如果有),以及
(2) 强制浏览器重新解析容器的全部内容(相比之下,使用insertAdjacentHTML
,浏览器只解析/插入添加的内容)
请注意,您也可以先将元素保存在变量中以避免重复:
const stockPriceElm = document.getElementById("stockprice");
for(var i=0; i<stockPrices.length; i++){
stockPriceElm.append(stockNames[i]+" ");
stockPriceElm.append(stockPrices[i]+" ");
stockPriceElm.insertAdjacentHTML('beforeend', "<br>");
}
或者,甚至更好:
const stockPriceElm = document.getElementById("stockprice");
for (var i = 0; i < stockPrices.length; i++) {
stockPriceElm.insertAdjacentHTML('beforeend', stockNames[i] + " " + stockPrices[i] + " <br>");
}
你应该选择innerHTML
function appendContent() { document.getElementById("stockprice").innerHTML += "<br>"; document.getElementById("stockprice").innerHTML += "New Data"; }
<p id="stockprice">Initial Content</p> <button onclick="appendContent()">Append</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.