开发者

Is there a way to validate a Sizzle selector?

Is there a way to validate (verify that its constructed correctly) a Sizzle 开发者_C百科selector without running it?


Well, as Russ says, since Sizzle interprets the selector, it cannot validate it without evaluating it.

However, you can catch the exception thrown by Sizzle to determine if a selector is valid or not:

function isSelectorValid(selector)
{
    try {
        $(selector);
    } catch (x) {
        return false;
    }
    return true;
}

Your can test this solution here.


EDIT: For the sake of history, my original (and overengineered) answer was:

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.


Not quite, the Sizzle engine isn't compiled so the only way to check the validity of the selector is to select it.

However, you can do something like this:

var selector = ...construct your selector ...
if ($(selector).length > 0) {
 // it worked.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜