簡體   English   中英

JavaScript appendChild文本節點不會換行

[英]JavaScript appendChild text node doesn't break line

JavaScript n00b在這里...
我在javascript中生成了一些html代碼,這些代碼將通過棱鏡HTML標記插件顯示為代碼。 單擊按鈕后,代碼會動態添加到<pre>標記中。

我的JavaScript代碼如下。 這是第2行中的文本,我需要在其中換行。 我已經試過了/ n,但是那行不通,只是一個空格。

var startLabelTag = document.createTextNode("text goes here");
startLabelTag.nodeValue = "<label><strong>" + elementNameFinal + "</strong></label>LINEBREAK HERE<select id='dropdownmenu' class='Custom_" + fieldNameFinal + "' onchange='selectChanged('@field[" + fieldNameFinal + "]',this.value);'>";
document.getElementById("dropdown-code").appendChild(startLabelTag);

以下是我嘗試創建的文本字符串,在其中將換行符放在文本LINEBREAK所在的位置。

<label><strong>" + elementNameFinal + "</strong></label>LINEBREAK HERE<select id='dropdownmenu' class='Custom_" + fieldNameFinal + "' onchange='selectChanged('@field[" + fieldNameFinal + "]',this.value);'>

您正在尋找這樣的東西嗎?

通過使用String.fromCharCode(10)您可以插入一個換行符,並使用pre標簽(或div帶有white-space: pre-wrap )可以看到/顯示該換行符。

 var elementNameFinal = "elementname", fieldNameFinal = "fieldname"; var startLabelTag = document.createTextNode("text goes here"); startLabelTag.nodeValue = "<label><strong>" + elementNameFinal + "</strong></label>" + String.fromCharCode(10) + "<select id='dropdownmenu' class='Custom_" + fieldNameFinal + "' onchange='selectChanged('@field[" + fieldNameFinal + "]',this.value);'>"; document.getElementById("dropdown-code").appendChild(startLabelTag); 
 <pre id="dropdown-code"></pre> 

邊注

當然,您也可以使用div ,建議使用CSS規則Niet the Dark Absol

<div id="dropdown-code"></div>

#dropdown-code {
  white-space: pre-wrap;
}

添加white-space: pre-wrap到容器的CSS中。

畢竟,如果您在HTML源代碼中鍵入換行符,結果中是否會出現空白行? 不。 並非沒有通過CSS使空白重要的地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM