gpt4 book ai didi

javascript - 如何使用 jQuery 替换列表项内容?

转载 作者:太空宇宙 更新时间:2023-11-04 13:42:20 24 4
gpt4 key购买 nike

我正在尝试制作一个按钮来替换 li 的内容。我在这里搜索了其他答案,但我得到了这个错误:Uncaught TypeError: Object li#element2 has no method 'replaceWith'

我已经尝试过 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>

最佳答案

错别字

缺少 $ 符号

$("#element2").replaceWith("This is the second element");
^

fiddle DEMO


NicoSantangelo 评论

你也不需要 $("li#element2") 因为 id 是唯一的所以用 $("#element2") 会更快不必使用标签选择器。


更好用.text()

fiddle DEMO

$(document).ready(function () {
$("#theButton").click(function () {
$("#element2").text("This is the second element")
});
});


更正您的标记关闭 li 标签

<ul id="theList">
<li id="element1">Element 1</li>
<li id="element2">Element 2</li>
<li id="element3">Element 3</li>
</ul>

关于javascript - 如何使用 jQuery 替换列表项内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19647985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com