这里是 jsfiddle 链接 - http://jsfiddle.net/howg59sg/5/
<div id='test1'>
<ul>
<li id="li1" friendName="foo">test 1</li>
<li id="li2" friendName="bar">test 2</li>
</ul>
</div>
function myclick() {
alert("clicked");
var elemId = "#li1";
var elemCollection = jQuery(elemId);
alert("len = " + elemCollection.length);
if (elemCollection.length) {
var selectedElem = elemCollection[0];
alert("id of the element to work on " + selectedElem.attributes["id"].value);
var stringToReplaceWith = "testing";
alert("friendname = " + selectedElem.attributes["friendname"].value);
//alert("html value of selected elem = " + selectedElem.html());
selectedElem.html(stringToReplaceWith);
} else {
alert("none");
}
}
如您所见,我正在尝试使用 jQuery 更新 li 元素的 html 内容。这会导致以下错误:
未捕获类型错误:未定义不是函数
我能够获取此 li 元素的属性,但 html() setter 失败。即使 getter 也会失败,我现在已经在代码中注释掉了......
有谁知道,这里可能出了什么问题?
感谢您的帮助。
最佳答案
您收到错误是因为 selectedElem
不是 jQuery 对象。
var selectedElem = elemCollection[0]; <-- gets the DOM node
selectedElem.html(stringToReplaceWith); <-- you treat it as a jQuery object
要么使用 .eq(0
) 以 jQuery 的形式获取元素,而不是括号表示法,然后使用 .attr()
读取属性 要么用 包装它>jQuery()
或使用 innerHTML
关于javascript - 在 li 元素上使用 jQuery 设置 html 会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28258482/