mct*_*sen 2 jquery jquery-selectors
我想检查一个字符串的'type'.特别是,我如何区分jQuery选择器字符串与其他字符串?换句话说,如何在以下代码中实现selectorTest?
var stringType = function( value ) {
var htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$/;
if ( htmlExpr.test(value) ) {
return "htmlstring";
}
if ( selectorTest ) {
return "selectorstring";
}
return "string";
}
Run Code Online (Sandbox Code Playgroud)
您可以在内部执行jQuery所做的事情,并使用以下正则表达式检查它是否为HTML :
/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/
Run Code Online (Sandbox Code Playgroud)
例如:
var stringType = function( value ) {
var htmlExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/;
if ( htmlExpr.test(value) ) {
return "htmlstring";
}
if ( selectorTest ) {
return "selectorstring";
}
return "string";
}
Run Code Online (Sandbox Code Playgroud)
请注意,在更新版本的jQuery中,还有另一个明确用于"以...开头<"和"以...结尾>"以检查正则表达式(仅用于速度)的检查. 核心看起来像这样(从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 );
}
Run Code Online (Sandbox Code Playgroud)