jQuery equivalent of || or ?? operator
Using plain JavaScript I can do stuff like this:
var ninjaTurtle = document.getElementById('raphael') ||
document.getElementById('leonardo');
If the first DOM lookup returns null
, which is falsy, the second lookup is evaluated.
The jQuery function $()
always returns i jQuery array-like object, even when no elements are matched. Even when empty, this object is not falsy, hence the following expression 开发者_高级运维will never evaluate the right hand side:
var ninjaTurtle = $('#raphael') || $('#leonardo');
So, what is the idiomatic way of doing this kind of fallback when using jQuery?
Checking the matched/returned element count will tell you if your selector matched something or not... fallback is a simple utility plugin which lets you do that gracefully...
jQuery.fn.fallback = function(elem) {
return 0 < this.length ? this : $(elem);
};
The best part of this function is you can chain as many as needed until you find a matched element..
$('#raphael').fallback('#leonardo').fallback('#kilik').dosomething();
var ninjaTurtle = $('#raphael').length ? $('#raphael') : $('#leonardo');
I don't see the way of doing it. The shortest things that comes to my mind is:
var ninjaTurtle = $('#raphael').length ? $('#raphael') : $('#leonardo');
精彩评论