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 人瀏覽

啟動您的職業

透過完成課程獲得認證

開始
廣告