簡體   English   中英

如何使用jQuery替換列表項內容?

[英]How to replace list item content using jQuery?

我正在嘗試制作一個可以取代李的內容的按鈕。 我在這里搜索了其他答案,但是我收到了這個錯誤:未捕獲TypeError:對象li#element2沒有方法'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");
^

小提琴演示


NicoSantangelo評論

你也不需要$("li#element2")它會更快與$("#element2")因為id是唯一的,所以不必使用它的標簽選擇器。


更好用.text()

小提琴演示

 $(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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM