jQuery.parseHTML()


jQuery.parseHTML( data [, context ] [, keepScripts ] )返回: Array

描述: 将字符串解析到一个DOM节点的数组中。

  • 添加的版本: 1.8jQuery.parseHTML( data [, context ] [, keepScripts ] )

    • data
      类型: String
      用来解析的HTML字符串。
    • context (默认: document)
      类型: Element
      DOM元素的上下文,在这个上下文中将创建的HTML片段。
    • keepScripts (默认: false)
      类型: Boolean
      一个布尔值,表明是否在传递的HTML字符串中包含脚本。

jQuery.parseHTML 使用原生的DOM元素的创建函数将字符串转换为一组DOM元素,然后,可以插入到文档中。

默认情况下,如果没有指定或给定null or undefinedcontext是当前的document。如果HTML被用在另一个document中,比如一个iframe,该frame的文件可以使用。

例子:

Create an array of Dom nodes using an HTML string and insert it into a div.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="log">
<h3>Content:</h3>
</div>
<script>
var $log = $( "#log" ),
str = "hello, <b>my name is</b> jQuery.",
html = $.parseHTML( str ),
nodeNames = [];
// Append the parsed HTML
$log.append( html );
// Gather the parsed HTML's node names
$.each( html, function( i, el ) {
nodeNames[i] = "<li>" + el.nodeName + "</li>";
});
// Insert the node names
$log.append( "<h3>Node Names:</h3>" );
$( "<ol></ol>" )
.append( nodeNames.join( "" ) )
.appendTo( $log );
</script>
</body>
</html>

Demo: