当未找到元素时,jQuery 是否可以抛出异常?

发布于 2024-12-02 09:08:15 字数 238 浏览 1 评论 0原文

我是 jQuery 的新手,我想简化对它无法找到的元素的处理,这是一个相当常见的问题。下面的代码显示了我的意思:

var category = $('select#Category');

现在,我可以检查返回的变量以查看是否未找到它,但我肯定更喜欢在这种情况下自动抛出异常。这对于 jQuery 来说是可能的吗?如果没有,是否有一些常见的习惯用法可以在 jQuery 之上实现这种自动错误检查?

I'm new to jQuery and I'd like to simplify the handling of elements it can't find, which is a fairly common problem. The following code shows what I mean:

var category = $('select#Category');

Now, I can inspect the returned variable to see if it wasn't found, but I'd definitely prefer an exception being thrown automatically in this case. Is this at all possible with jQuery? If not, is there some common idiom for implementing such automatic error checking on top of jQuery?

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

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

发布评论

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

评论(2

那伤。 2024-12-09 09:08:16

我不确定是否有任何现有功能可以做到这一点,但我认为如果您在使用 jQuery 之前将其放在页面顶部,但在加载它之后,这应该对您有用:

(function(){
    var _$ = $;
    $ = function(){
        var $res = _$.apply(0, arguments);
        if(!$res.length && typeof arguments[0] === 'string')
            throw 'No element Found: ' + arguments[0];
        return $res;
    }
    $ = _$.extend(true, $, _$);
})();

JSFiddle 示例

I'm not sure of any existing functionality to do that, but I think this should work for you if you put it at the top of the page before using jQuery, but after loading it:

(function(){
    var _$ = $;
    $ = function(){
        var $res = _$.apply(0, arguments);
        if(!$res.length && typeof arguments[0] === 'string')
            throw 'No element Found: ' + arguments[0];
        return $res;
    }
    $ = _$.extend(true, $, _$);
})();

JSFiddle Example

黑寡妇 2024-12-09 09:08:16

我只是使用这种方法:

if (category.length == 1) {
// node has been found (and is the only one in the dom)
}

我认为抛出异常不是一个好主意:P

I simply use this approach:

if (category.length == 1) {
// node has been found (and is the only one in the dom)
}

I think that throwing an exception is not a good idea :P

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