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中默认的htmlProfilter函数将贪婪地确保所有标记都符合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 );
};