jQuery 中的 text() 和 html() 有什麼區別?


jQuery 提供了許多用於處理屬性的方法。這些都是與 DOM 相關的函式。屬性包括 text() 和 html()。

  • text() – 此方法設定或返回所選元素的文字內容。
  • html() – 此方法設定或返回所選元素的內容。

示例

你可以嘗試執行以下程式碼來了解如何使用 text() 和 html() 方法處理屬性 −

線上演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $("#button1").click(function(){
      alert("Using text()- " + $("#demo").text());
   });
   $("#button2").click(function(){
      alert("Using html()- " + $("#demo").html());
   });
});
</script>
</head>
<body>

<p id="demo">This is <b>demo</b> text.</p>

<button id="button1">Text</button>
<button id="button2">HTML</button>

</body>
</html>

更新日期: 2020 年 2 月 14 日

423 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告