有没有办法验证 Sizzle 选择器?

发布于 2024-11-06 05:44:33 字数 49 浏览 3 评论 0原文

有没有一种方法可以在不运行 Sizzle 选择器的情况下验证(验证其构造是否正确)?

Is there a way to validate (verify that its constructed correctly) a Sizzle selector without running it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

红颜悴 2024-11-13 05:44:33

好吧,正如 Russ 所说,由于 Sizzle 解释选择器,因此它无法在不评估它的情况下验证它。

但是,您可以捕获 Sizzle 引发的异常来确定选择器是否有效:

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

您可以在此处测试此解决方案


编辑:为了历史的缘故,我最初的(并且过度设计的)答案是:

但是,可以暂时覆盖 Sizzle 的错误管理,以便从上次解析操作的错误状态中提取布尔值。以下解决方案利用了 jQuery 通过 $.find 公开 Sizzle 的事实(到目前为止):

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;
    }
}

这可以说是一个可怕的 hack,但它有效:您可以测试它 此处

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.

慕烟庭风 2024-11-13 05:44:33

不完全是,Sizzle 引擎未编译,因此检查选择器有效性的唯一方法是选择它。

但是,您可以执行以下操作:

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

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.
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文