如何区分jQuery选择器字符串与其他字符串 [英] How do I distinguish jQuery selector strings from other strings
本文介绍了如何区分jQuery选择器字符串与其他字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检查字符串的'type'。特别是,我如何区分jQuery选择器字符串与其他字符串?换句话说,如何在以下代码中实现selectorTest?
I want to check the 'type' of a string. Particularly, how do I distinguish jQuery selector strings from other strings? In other words, how should selectorTest be implemented in the following code?
var stringType = function( value ) {
var htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$/;
if ( htmlExpr.test(value) ) {
return "htmlstring";
}
if ( selectorTest ) {
return "selectorstring";
}
return "string";
}
推荐答案
你可以在内部执行jQuery所做的工作并使用以下正则表达式:
/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/
例如:
var stringType = function( value ) {
var htmlExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/;
if ( htmlExpr.test(value) ) {
return "htmlstring";
}
if ( selectorTest ) {
return "selectorstring";
}
return "string";
}
请注意,最近版本的jQuery,还有另一项检查使用<
和以结尾
跳过正则表达式(纯粹为速度)。在核心中支票看起来像这样(从jQuery开始) 1.6.1):
Note that in more recent versions of jQuery, there's another check explicitly for "starting with <
" and "ending with >
" to skip the regex (purely for speed). The check looks like this in core (as of 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 );
}
这篇关于如何区分jQuery选择器字符串与其他字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文