简体   繁体   English

我怎样才能附加一个<br>使用 document.getElementByID?

[英]How can I append a <br> using document.getElementByID?

I'm trying to append a <p> element using DOM to append a stock symbol, and stock price, then go to a new line using <br> , but when I run this:我正在尝试使用 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>");
}

it literally adds the text <br> to my "stockprice" element.它实际上将文本<br>添加到我的“股票价格”元素中。 What is the proper way to do this?这样做的正确方法是什么?

Use insertAdjacentHTML instead:使用insertAdjacentHTML代替:

 document.body.append('content'); document.body.insertAdjacentHTML('beforeend', '<br>'); document.body.append('more content');

I'd recommend against concatenating with the existing innerHTML because that will我建议不要与现有的innerHTML连接,因为那样会

(1) corrupt existing listeners inside the container, if any, and (1) 破坏容器内现有的侦听器(如果有),以及

(2) force the browser to re-parse the entire contents of the container (in contrast, with insertAdjacentHTML , the browser only parses/inserts what gets added ) (2) 强制浏览器重新解析容器的全部内容(相比之下,使用insertAdjacentHTML ,浏览器解析/插入添加的内容

Note that you can also save the element in a variable first to avoid repeating yourself:请注意,您也可以先将元素保存在变量中以避免重复:

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>");
}

Or, even better:或者,甚至更好:

const stockPriceElm = document.getElementById("stockprice");
for (var i = 0; i < stockPrices.length; i++) {
  stockPriceElm.insertAdjacentHTML('beforeend', stockNames[i] + " " + stockPrices[i] + " <br>");
}

You should go for innerHTML你应该选择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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM