我想检查字符串的“类型”。特别是,如何区分 jQuery 选择器字符串和其他字符串?也就是说,下面的代码中selectorTest应该如何实现呢?
var stringType = function( value ) {
var htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$/;
if ( htmlExpr.test(value) ) {
return "htmlstring";
}
if ( selectorTest ) {
return "selectorstring";
}
return "string";
}
You can 做 jQuery 所做的事情 https://github.com/jquery/jquery/blob/master/src/core.js#L104内部并检查它是否是 HTML以下正则表达式 https://github.com/jquery/jquery/blob/master/src/core.js#L20:
/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/
e.g.:
var stringType = function( value ) {
var htmlExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/;
if ( htmlExpr.test(value) ) {
return "htmlstring";
}
if ( selectorTest ) {
return "selectorstring";
}
return "string";
}
请注意,在最新版本的 jQuery 中,还有另一张支票 https://github.com/jquery/jquery/blob/master/src/core.js#L99明确表示“从<
” 和 “ 结尾为>
" 跳过正则表达式(纯粹是为了速度)。支票看起来像这样 https://github.com/jquery/jquery/blob/master/src/core.js#L99在核心中(从 jQuery 1.6.1 开始):
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = quickExpr.exec( selector );
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)