jQuery 中的 html() 方法有什麼作用?


html() 方法設定或返回選定元素的內容。jQuery 有一些方法可用來處理屬性,包括 html() 方法。這些方法都與 DOM 相關。屬性包括:

  • text() — 此方法設定或返回選定元素的文字內容。
  • html() — 此方法設定或返回選定元素的內容。
  • val() — 此方法設定或返回表單欄位的值。

示例

你可以嘗試執行以下程式碼來學習如何使用 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>

更新於:14-2 月-2020

115 次瀏覽

開啟你的 職業生涯

完成課程獲取認證

開始
廣告