【发布时间】:2014-10-24 06:34:24
【问题描述】:
我正在尝试使用函数 .text() 将文本写入元素范围,但出现此错误 UncaughtTypeError: undefined is not a function,我也试过函数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
【问题讨论】:
-
.text()是 jQuery 的函数。使用closeSpan.textContent = "Close";不知道什么是DOM版本的jQuery的.append() -
innerHTML/innerText/textContent是一个属性,而不是一个函数 (span.innerHTML = 'Close')。createTextNode只创建了一个文本节点,你还需要将它添加到元素中(span.appendChild(document.createTextNode('Close')))。 -
“我做错了什么?” - 你在混淆 jQuery 和 DOM 方法。你能解释一下为什么你首先打电话给
document.createElement()吗? (也看看documentation for DOM Node objects,那里既不存在.text()也不存在.append()。)
标签: javascript jquery dom