您可以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