[英]How to add text into span after document.createElement(“span”);?
我正在嘗試使用函數.text()將文本寫入元素范圍,但是我收到此錯誤UncaughtTypeError:undefined不是函數 ,我還嘗試了函數append(),innerHtml(),createTextNode()但沒有成功。
我究竟做錯了什么?
var closeSpan = document.createElement("span");
closeSpan.setAttribute("class","sr-only");
closeSpan.text("Close"); //UncaughtTypeError: undefined is not a function
要么
var closeSpan = document.createElement("span");
closeSpan.setAttribute("class","sr-only");
closeSpan.append("Close"); //UncaughtTypeError: undefined is not a function
由於您從純DOM代碼開始,我建議繼續使用純DOM代碼:
var closeSpan = document.createElement("span");
closeSpan.setAttribute("class","sr-only");
closeSpan.textContent = "Close";
換句話說,只需將textContent
設置為您想要的值。
如果與IE 8或更早版本的兼容性對您很重要,請注意那些舊版瀏覽器不存在textContent
。 對於那些較舊的,你必須使用innerText
(適用於IE 8,但不是任何標准的一部分)或innerHTML
。 有關這些字段之間差異的討論,請參閱textContent
上的MDN頁面(我鏈接到上面)。
如果你不想使用jquery,你會用closeSpan.appendChild
和document.createTextNode
像這樣:
var closeSpan = document.createElement("span");
closeSpan.setAttribute("class","sr-only");
closeSpan.appendChild(document.createTextNode("Close"));
此方法可最大化跨瀏覽器兼容性。 它適用於所有瀏覽器,包括舊版本的IE。
如果您確實想使用jquery,可以在一行中執行此操作:
var closeSpan = $("<span></span>").addClass("sr-only").text("Close")[0];
你也可以嘗試一下
var closeSpan = document.createElement("span");
closeSpan.setAttribute("class","sr-only");
closeSpan.html("Close");
假設您要將“span”標記添加到ID為“myDiv”的div:
var span = $("span"); // create element span
$(span).html("your text"); // add text
$("#myDiv").append($(span)); // append it to the div element
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.