我正在嘗試創建p標簽并在其中span使用insertAdjacentHTML方法并為每個標簽賦予唯一的ID,然后我想更改或更新textContent,但我不知道它不起作用的原因是什么?如果您有解決方案,請幫助我。
const wraper = document.querySelector("#wraper")
const place2 = "afterbegin";
const textOfTimerTile = `
<div >
<p id="program"><span id="programData"></span></p>
<p id="machineId"><span id="machineIdData"></span></p>
</div>
`;
wraper.insertAdjacentHTML(place2, textOfTimerTile);
const program = document.getElementById("program");
const programData = document.getElementById("programData");
const machineId = document.getElementById("machineId");
const machineIdData = document.getElementById("machineIdData");
program.textContent = "Program";
programData.textContent = "Program Span";
machineId.textContent= "Machine ID";
machineIdData.textContent= "Machine Span";
console.log("p tag ", program);
console.log("span ", programData)
#program, #machineId{
width: 150px;
height: 100px;
background-color: green
}
#programData, #machineIdData{
width:100px;
height: 60px;
background-color: red;
}
<div id="wraper"></div>
uj5u.com熱心網友回復:
根據MDN textContent:
textContent 和 innerText 在更改時都會洗掉子節點。在這樣做之后,不可能將節點再次插入任何其他元素或相同的元素。
意味著你覆寫你<p>的內部元素。如果您愿意,我建議使用innerHTML并添加文本,而不是使用textContent.
但是,由于您設定了新innerHTML元素,因此您需要再次獲取內部元素。
總結 -
const wraper = document.querySelector("#wraper")
const place2 = "afterbegin";
const textOfTimerTile = `
<div >
<p id="program"><span id="programData"></span></p>
<p id="machineId"><span id="machineIdData"></span></p>
</div>
`;
wraper.insertAdjacentHTML(place2, textOfTimerTile);
const program = document.getElementById("program");
const machineId = document.getElementById("machineId");
program.innerHTML = "Program" program.innerHTML;
const programData = document.getElementById("programData");
programData.innerHTML = "Program Span";
machineId.innerHTML = "Machine ID" machineId.innerHTML;
const machineIdData = document.getElementById("machineIdData");
machineIdData.innerHTML = "Machine Span";
#program,
#machineId {
width: 150px;
height: 100px;
background-color: green
}
#programData,
#machineIdData {
width: 500px;
height: 60px;
background-color: red;
}
<div id="wraper"></div>
uj5u.com熱心網友回復:
當您運行時,program.textContent = "Program";您實際上是從頁面中洗掉跨度(您可以在瀏覽器的開發工具中看到)。
你可以做的是 program.insertAdjacentText('afterbegin', 'Program')
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/410918.html
標籤:
上一篇:我嘗試從reactnative中的另一個js檔案匯入JS檔案中的陣列資料,并嘗試在reactnative中檢查陣列的長度
