返回值:Stringhtml()
Get the HTML contents of the first element in the set of matched elements.
-
1.0 新增html()
This method is not available on XML documents.
In an HTML document, we can use .html()
to get the contents of any element. If the selector expression matches more than one element, only the first one's HTML content
is returned. Consider this code:
$('div.demo-container').html();
In order for the following <div>
's content to be retrieved, it would have to be the first one with class="demo-container"
in the document:
<div class="demo-container"> <div class="demo-box">Demonstration Box</div> </div>
The result would look like this:
<div class="demo-box">Demonstration Box</div>
This method uses the browser's innerHTML
property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example,
Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.
示例:
Click a paragraph to convert it from html to text.
<!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="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>