jQuery相当于||要么 ??操作者 [英] jQuery equivalent of || or ?? operator
问题描述
使用纯JavaScript我可以这样做:
Using plain JavaScript I can do stuff like this:
var ninjaTurtle = document.getElementById('raphael') ||
document.getElementById('leonardo');
如果第一个DOM查找返回 null
,这是假的,第二次查找被评估。
If the first DOM lookup returns null
, which is falsy, the second lookup is evaluated.
jQuery函数 $()
总是返回i jQuery数组 - 喜欢对象,即使没有元素匹配。即使是空的,这个对象也不是假的,因此下面的表达式永远不会评估右侧:
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');
那么,使用jQuery时这种回退的惯用方法是什么?
So, what is the idiomatic way of doing this kind of fallback when using jQuery?
推荐答案
检查匹配/返回的元素数将告诉您选择器是否匹配...
fallback 是一个简单的实用程序插件,可让您优雅地执行此操作...
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();
这篇关于jQuery相当于||要么 ??操作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!