当未找到元素时,jQuery 是否可以抛出异常?
我是 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定是否有任何现有功能可以做到这一点,但我认为如果您在使用 jQuery 之前将其放在页面顶部,但在加载它之后,这应该对您有用:
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:
JSFiddle Example
我只是使用这种方法:
我认为抛出异常不是一个好主意:P
I simply use this approach:
I think that throwing an exception is not a good idea :P