DIV CSS 佈局教程網

用 jQuery 取得標籤的文字內容與 HTML 內容
編輯:JQuery特效代碼     

本文示範如何使用 jQuery 的 text() 與 html() 方法,分別取得指定標籤的文字內容或 HTML 內容。

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    alert("Text: " + $("#test").text());
  });
  $("#btn2").click(function(){
    alert("HTML: " + $("#test").html());
  });
});
</script>
</head>
<body>
<p id="test">This is some <b>bold</b> text in a paragraph.</p>
<button id="btn1">Show Text</button>
<button id="btn2">Show HTML</button>
</body>
</html>

差別在於:text() 只取純文字(會濾掉 HTML 標籤),而 html() 會連內部的標籤結構一起取出。這兩個方法除了讀取,也能帶入參數用來設定內容。希望本文對大家的 jQuery 開發有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved