Is it possible to have jQuery throw an exception when an element isn't found?
I'm new to jQuery 开发者_如何学Cand 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?
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
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
精彩评论