jQuery.htmlPrefilter()


jQuery.htmlPrefilter( html )返回: String

描述: 通过jQuery操作方法修改和过滤HTML字符串。

这种方法很少需要直接调用。反而可以使用这个方法作为修改现有jQuery操作方法的一个切入点。 例如,从传入HTML字符串中删除所有<del>标签,可以这么做:

1
2
3
4
5
6
var htmlPrefilter = $.htmlPrefilter,
rdel = /<(del)(?=[\s>])[\w\W]*?<\/\1\s*>/gi;
$.htmlPrefilter = function( html ) {
return htmlPrefilter.call( this, html ).replace( rdel, "" );
};

这个函数也可以被重写,以便绕过某些边缘情况的问题。 jQuery中默认的htmlPrefilter函数将贪婪地确保所有的标签都符合XHTML标准。 这意味着包括任何看起来像一个HTML标签的内容,但实际上他可能是一个字符串 (例如

<a title="<div />"><>
) 。 jQuery.htmlPrefilter()函数可以绕过他:

1
2
3
4
$.htmlPrefilter = function( html ) {
// Return HTML strings unchanged
return html;
};

然而,尽管上述解决办法非常简短, 它把负担给你,确保在任何HTML字符串都符合XHTML标准。 此问题的更彻底的解决将是这样的:

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
36
37
38
39
40
41
42
43
44
var panything = "[\\w\\W]*?",
// Whitespace
// https://html.spec.whatwg.org/multipage/infrastructure.html#space-character
pspace = "[\\x20\\t\\r\\n\\f]",
// End of tag name (whitespace or greater-than)
pnameEnd = pspace.replace( "]", ">]" ),
// Tag name (a leading letter, then almost anything)
// https://html.spec.whatwg.org/multipage/syntax.html#tag-open-state
// https://html.spec.whatwg.org/multipage/syntax.html#tag-name-state
pname = "[a-z]" + pnameEnd.replace( "[", "[^/\\0" ) + "*",
// Void element (end tag prohibited)
// https://html.spec.whatwg.org/multipage/syntax.html#void-elements
pvoidName = "(?:area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|" +
"source|track|wbr)(?=" + pnameEnd + ")",
// Attributes (double-quoted value, single-quoted value, unquoted value, or no value)
// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
pattrs = "(?:" + pspace + "+[^\\0-\\x20\\x7f-\\x9f=\"'/>]+(?:" + pspace + "*=" + pspace +
"*(?:\"" + panything + "\"|'" + panything + "'|" +
pnameEnd.replace( "[", "[^" ) + "*(?!/)" +
")|))*" + pspace + "*",
// Trailing content of a close tag
pcloseTail = "(?:" + pspace + panything + "|)",
rspecialHtml = new RegExp(
// Non-void element that self-closes: $1–$5
"(<)(?!" + pvoidName + ")(" + pname + ")(" + pattrs + ")(\\/)(>)|" +
// No-innerHTML container (element, comment, or CDATA): $6
"(<(script|style|textarea)" + pattrs + ">" + panything + "<\\/\\7" + pcloseTail + ">|" +
"<!--" + panything + "--)",
"gi"
),
// "<"; element name; attributes; ">"; "<"; "/"; element name; ">"; no-innerHTML container
pspecialReplacement = "$1$2$3$5$1$4$2$5$6";
$.htmlPrefilter = function( html ) {
return ( html + "" ).replace( rspecialHtml, pspecialReplacement );
};