2016-03-03 53 views
-2

我正在尋找使用Jquery追加將文本追加到預先存在的div元素。我也想擁有幾個元素「模板」,並在這些元素中添加更多文本(請參閱代碼段)。使用javascript將文本追加到HTML標記

var template = { template1: "<p class='someclass'></p>" }, 
    o = $('.divClass'); 
    o.append(template.template1); // Append text inside P tag 
+0

如果DIV的ID爲'example',您可以用'VAR元素=的document.getElementById( 「例如」);',然後就'element.innerHTML + = 「額外的東西」;' – Aeolingamenfel

回答

0

你可能想嘗試這樣的:

var template = { template1: $("<p class='someclass'></p>") }, 
    o = $('.divClass'); 

// Set template and append to container 
var currentTemplate = template.template1; 
o.append(currentTemplate); 

// Get current text and append content to the end 
var textNode = currentTemplate.text() + "Append Content"; 
currentTemplate.text(textNode); 

基本上,我創建了款,因爲它是自己的節點,而不是一個文本字符串,所以我有修改的元素更大的靈活性。我通常會等待將元素追加到我的容器中,直到完成修改後,但它會以任何方式工作。

如果您不需要附加到當前文本,您還可以跳過獲取當前文本。根據您的其他評論,您可以遍歷底部,選擇對象中的每個模板和文本節點並將其附加到容器。

+0

謝謝!這應該工作! –

0

不是將p元素存儲爲字符串,而是將其作爲元素存儲。如果它已經創建,使用的getElementById()或getElementByClassName(),如果你現在正在打造它,使用

var myPElement = document.createElement("p"); 

然後,您可以自由更改或添加到myPElement包含文本。

myPElement.innerHTML = "set text equal to this"; 
myPElement.innerHTML += "append this"; 
+0

我喜歡這個主意,但我不確定它如何很好地轉換爲我所需要的。基本上,我想添加一個循環來添加多個p元素和來自對象數組的文本。 所以它會看起來像: '爲(索引= 0;索引

+0

http://www.w3schools.com/jsref /met_node_appendchild.asp循環遍歷數組中的對象,爲每個對象創建一個ap元素和一個textElement。然後將textElement附加到p元素,並將p元素附加到父容器。他們展示瞭如何在所提供的鏈接中完成所有這些。 – Observer

相關問題