您可以do what jQuery does内部和检查它是否是HTML或不the following regex:
/^(?:[^<]*(<[\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,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);
}
你不能。 jQuery选择器几乎可以做任何事情。 – JohnP 2011-05-15 10:28:29