.prepend不是一个函数
请考虑以下示例代码:
$(document).ready(function(){ $("#btn1").click(function(){ var btn = document.createElement("BUTTON"); btn.prepend("Prepended text. "); }); }); This is a paragraph.
上面的代码在控制台中抛出错误:
btn.prepend不是一个函数
为什么会出现此错误? 请提出解决方案。 谢谢
请不要关注W3Schools的低质量文章。 为您的解决方案:
-
btn
不是jQuery对象。 它是一个JavaScriptHTMLElement
。 -
.prepend()
函数是一个jQuery函数。
你现在的代码应该是:
$(document).ready(function(){ $("#btn1").click(function(){ var btn = $(this); btn.prepend("Prepended text. "); }); });
工作片段
$(document).ready(function(){ $("#btn1").click(function(){ var btn = $(this); btn.prepend("Prepended text. "); }); });
This is a paragraph.
出现错误是因为createElement()
返回没有append()
方法的DOMElement; 这只适用于jQuery对象。 您需要将DOMElement包装到jQuery对象,或者更好的是,在jQuery中创建元素:
$("#btn1").click(function(){ var btn = $(''); btn.prepend("Prepended text. "); // add the btn to the DOM somewhere... });