我想检查字符串的'type'。特别是,我如何区分jQuery选择器字符串与其他字符串?换句话说,如何在以下代码中实现selectorTest?
var stringType = function( value ) {
var htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$/;
if ( htmlExpr.test(value) ) {
return "htmlstring";
}
if ( selectorTest ) {
return "selectorstring";
}
return "string";
}
答案 0 :(得分:5)
您可以在内部do what jQuery does使用the following regex检查HTML是否为HTML:
/^(?:[^<]*(<[\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中,there's another check明确表示“以<
开头”和“以>
结尾”以跳过正则表达式(纯粹为了速度)。核心The check looks like this(从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 );
}
答案 1 :(得分:-2)
也许($(value).size()>0
)?
它将测试选择器是否被识别。
但在我看来,这有点奇怪......