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>
廣告