javascript 如何使用 jQuery 替换列表项内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19647985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to replace list item content using jQuery?
提问by Miles Pfefferle
I'm trying to make a button that will replace the content of a li. I've searched other answers on here, but I get this error: Uncaught TypeError: Object li#element2 has no method 'replaceWith'
我正在尝试制作一个按钮来替换 li 的内容。我在这里搜索了其他答案,但我收到了这个错误:Uncaught TypeError: Object li#element2 has no method 'replaceWith'
I've tried replaceWith, .html, and .text, but they all have the same Here's my page:
我尝试过 replaceWith、.html 和 .text,但它们都有相同的 这是我的页面:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#theButton").click(function(){
("li#element2").replaceWith("This is the second element")
});
});
</script>
</head>
<body>
<h1 id="header">The document header.</h1>
<p>Value: <input type="text" id="theInput" value="" size=10>
<ul id="theList">
<li id="element1">Element 1
<li id="element2">Element 2
<li id="element3">Element 3
</ul>
<div id="theDiv"></div>
<input type="button" id="theButton" value="click me!""></p>
</body>
</html>
回答by Tushar Gupta - curioustushar
Typo
错别字
missing $
sign
缺少$
标志
$("#element2").replaceWith("This is the second element");
^
评论人 NicoSantangelo尼科桑坦吉洛
You also don't need $("li#element2")
it will be faster with $("#element2")
as id is unique so don't have to use tag selector with it.
您也不需要 $("li#element2")
它会更快,$("#element2")
因为 id 是唯一的,所以不必使用标签选择器。
Better use .text()
更好地使用.text()
$(document).ready(function () {
$("#theButton").click(function () {
$("#element2").text("This is the second element")
});
});
更正您的标记关闭
li
li
标签<ul id="theList">
<li id="element1">Element 1</li>
<li id="element2">Element 2</li>
<li id="element3">Element 3</li>
</ul>