.html()
.html() 返回: String
描述: 從匹配的第一個元素中獲取HTML內(nèi)容。
version added: 1.0.html()
這個方法對 XML 文檔無效。
在一個 HTML 文檔中, 我們可以使用 .html() 方法來獲取任意一個元素的內(nèi)容。 如果選擇器匹配多于一個的元素,那么只有第一個匹配元素的 HTML 內(nèi)容會被獲取。 考慮下面的代碼:
$('div.demo-container').html();
下文的獲取的<div>的內(nèi)容, 必定是在文檔中的第一個class="demo-container"的div中獲取的:
<div class="demo-container"> <div class="demo-box">Demonstration Box</div> </div>
結(jié)果如下:
<div class="demo-box">Demonstration Box</div>
舉例:
點擊段落將HTML轉(zhuǎn)化為文本
<!DOCTYPE html>
<html>
<head>
<style>
p { margin:8px; font-size:20px; color:blue;
cursor:pointer; }
b { text-decoration:underline; }
button { cursor:pointer; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<p>
<b>Click</b> to change the <span id="tag">html</span>
</p>
<p>
to a <span id="text">text</span> node.
</p>
<p>
This <button name="nada">button</button> does nothing.
</p>
<script>
$("p").click(function () {
var htmlStr = $(this).html();
$(this).text(htmlStr);
});
</script>
</body>
</html>
Demo:
.html( htmlString ) 返回 jQuery
描述: 設置每一個匹配元素的html內(nèi)容。
-
version added: 1.0.html( htmlString )
htmlString用來設置每個匹配元素的一個HTML 字符串。
-
version added: 1.4.html( function(index, html) )
function(index, html)用來返回設置HTML內(nèi)容的一個函數(shù)。接收元素的索引位置和元素舊的HTML作為參數(shù)。。
這個 .html() 方法對 XML 文檔無效.
我們可以使用 .html() 來設置元素的內(nèi)容,在這些元素的任何內(nèi)容完全被新的內(nèi)容取代??紤]以下的HTML:
<div class="demo-container"> <div class="demo-box">Demonstration Box</div> </div>
我們可以像這樣設置 <div class="demo-container">的HTML內(nèi)容:
$('div.demo-container')
.html('<p>All new content. <em>You bet!</em></p>');
這行代碼將替換 <div class="demo-container">里的所有內(nèi)容
<div class="demo-container"> <p>All new content. <em>You bet!</em></p> </div>
在 jQuery 1.4中, .html() 方法允許我們通過函數(shù)來傳遞HTML內(nèi)容。
$('div.demo-container').html(function() {
var emph = '<em>' + $('p').length + ' paragraphs!</em>';
return '<p>All new content for ' + emph + '</p>';
});
給定一個擁有6個段落的HTML文檔,在這個例子中將設置 <p>All new content for <em>6 paragraphs!</em></p>為<div class="demo-container">的新HTML內(nèi)容:
舉例
例子: 為每個div設置一些內(nèi)容。
<!DOCTYPE html>
<html>
<head>
<style>
.red { color:red; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<span>Hello</span>
<div></div>
<div></div>
<div></div>
<script>$("div").html("<span class='red'>Hello <b>Again</b></span>");</script>
</body>
</html>
Demo:
例子: 添加了一些html到每個div,然后立刻做進一步的操作來插入的HTML。
<!DOCTYPE html>
<html>
<head>
<style>
div { color:blue; font-size:18px; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<script>
$("div").html("<b>Wow!</b> Such excitement...");
$("div b").append(document.createTextNode("!!!"))
.css("color", "red");
</script>
</body>
</html>