我需要在 DIV 元素內的段落中動態設定文本。我知道 divID 并且可以使用 get document.getElementById(divID) 通過 id 獲取 div 這將回傳以下內容:
<div id="mynote72031" class="mydiv" ondrop="drop(event,this.id)" ondragover="allowDrop(event)" style="cursor: move; display: block; top: 19px; left: 19px; width: 375px;">
<a style="top:0px; right:5px; position:absolute; color:#F00" href="javascript:;" onclick="hideElement(this)">X</a>
<p id="noteContent1" ondblclick="editContent(this)">Note Number: 1</p>
</div>
該函式應如下所示:
function updateNote(divID, paragraphInnerHTML) {
var updateNoteP = document.getElementById(divID);
//Update Paragraph inside the DIV here
}
注意段落的id總是noteContent1
uj5u.com熱心網友回復:
有兩種方法可以更改 HTML 標記中的文本
function updateNote(divID, paragraphInnerHTML) {
var updateNoteP = document.getElementById(divID);
//Update Paragraph inside the DIV here
let $targetEle = updateNoteP.childNodes[1]
// use innerHTML
$targetEle.innerHTML = paragraphInnerHTML
// or textContext
$targetEle.textContent = paragraphInnerHTML
}
uj5u.com熱心網友回復:
您可以使用Node.lastChild訪問p標簽,因為它是標簽中的最后一個div元素
function updateNote(divID, paragraphInnerHTML) {
var updateNoteP = document.getElementById(divID);
//Update Paragraph inside the DIV here
let pElement = updateNoteP.lastChild;
pElement.innerHTML = paragraphInnerHTML;
}
uj5u.com熱心網友回復:
與您的變數名稱非常接近,這假定它是您要使用的 html。如果它只是一個字串,您可以改用 updateNoteP.innerText
如果您將 pID 作為“noteContent1”傳遞,這將更改 P 的內容
function updateNote(pID, paragraphInnerHTML) {
var updateNoteP = document.getElementById(divID);
// check that element is found
if (updateNoteP) {
// update inner html
updateNoteP.parentElement.children[1].innerHTML = paragraphInnerHTML
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/438950.html
標籤:javascript html dom
