有没有办法在不运行 Sizzle 选择器的情况下验证(验证其构造是否正确)?
问问题
816 次
2 回答
7
好吧,正如 Russ 所说,由于 Sizzle 解释了选择器,它无法在不评估它的情况下验证它。
但是,您可以捕获 Sizzle 抛出的异常以确定选择器是否有效:
function isSelectorValid(selector)
{
try {
$(selector);
} catch (x) {
return false;
}
return true;
}
您可以在此处测试此解决方案。
编辑:为了历史,我原来的(和过度设计的)答案是:
However, it's possible to temporarily override Sizzle's error management in order to extract a boolean value from the error status of its last parse operation. The following solution takes advantage of the fact that jQuery exposes Sizzle through $.find
(so far):
function isSelectorValid(selector)
{
var oldErrorMethod = $.find.error;
try {
$.find.error = function(msg) {
valid = false;
oldErrorMethod(msg);
};
$(selector);
return true;
} catch (x) {
return false;
} finally {
$.find.error = oldErrorMethod;
}
}
That can arguably be considered as a horrible hack, but it works: you can test it here.
于 2011-05-10T16:36:17.813 回答
0
不完全是,Sizzle 引擎没有被编译,所以检查选择器有效性的唯一方法是选择它。
但是,您可以执行以下操作:
var selector = ...construct your selector ...
if ($(selector).length > 0) {
// it worked.
}
于 2011-05-10T16:03:02.437 回答