[英]How can I add an “img” tag to a “p” element in basic Javascript?
因此,我試圖在“ p”元素內添加“ img”標簽。 但是,我似乎找不到如何設置“ img”標簽屬性。
我必須創建這個:
<p class="titre-recherche"><label>chaîne de caractères saisie</label><img src="croix30.jpg" class="icone-croix"/>value</p>
我嘗試過:創建具有不同屬性的img元素,並將其附加到“ p”元素上:
imgp = document.createElement("IMG")
imgp.setAttribute("src", "croix30.jpg")
imgp.setAttribute("class", "icone-croix")
divp.appendChild(imgp)
將img直接附加到原始節點(這很丑):
document.getElementById("recherches-stockees").appendChild(divp).appendChild(imgp)
這是我的整個部分,並附有評論:
var saisie = document.getElementById('zone_saisie').value
// Create "p"
var divp = document.createElement("P")
// set "p" attributes
divp.setAttribute("class", "titre-recherche")
divp.setAttribute("label", "chaîne de caractères saisie")
// divp.setAttribute("img", "src=\"croix30.jpg\" class=\"icone-croix\"")
divp.setAttribute("img", "")
divp.getAttribute("img").setAttribute("src", "croix30.jpg")
.setAttribute("class", "icone-croix")
// Set "p" text
var t = document.createTextNode(saisie)
divp.appendChild(t)
// Create "img"
// imgp = document.createElement("IMG")
// Set "img" attributes
// imgp.setAttribute("src", "croix30.jpg")
// imgp.setAttribute("class", "icone-croix")
// Link "p" and "img"
// divp.appendChild(imgp)
document.getElementById("recherches-stockees").appendChild(divp)
// document.getElementById("recherches-stockees").appendChild(imgp)
最終輸出應該是帖子開頭給出的行。 預先感謝您的幫助,希望這很清楚。
img
元素不是屬性,這就是使用setAttribute
無效的原因。
您的代碼是執行此操作的正確方法:
imgp = document.createElement("IMG")
imgp.setAttribute("src", "croix30.jpg")
imgp.setAttribute("class", "icone-croix")
divp.appendChild(imgp)
也就是說,這些屬性反映為屬性,因此:
imgp = document.createElement("IMG")
imgp.src = "croix30.jpg"
imgp.className = "icone-croix" // Note it's className, not class when it's a property
divp.appendChild(imgp)
在這兩種情況下,您都需要對img
之前的label
元素執行相同的操作。
或者,您可以使用insertAdjacentHTML
:
divp.insertAdjacentHTML("<label>chaîne de caractères saisie</label><img src='croix30.jpg' class='icone-croix'>")
或者由於您剛剛創建了divp
並且其中沒有任何其他內容,因此您可以分配給innerHTML
。
divp.innerHTML = "<label>chaîne de caractères saisie</label><img src='croix30.jpg' class='icone-croix'>"
(在上述所有情況下,您仍然需要document.getElementById("recherches-stockees").appendChild(divp)
行。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.