admin管理员组文章数量:1295740
JavaScript has very nice syntax for fallbacks and defaults, as long as unsuccessful calls return a falsy value:
var element = findElement() || findSomeOtherElement() || makeALastAttempt();
jQuery selectors are, however, truthy even when they are empty.
Is there an elegant way if saying "I want the element at this selector, and if it does not exist, then the element at that selector"?
JavaScript has very nice syntax for fallbacks and defaults, as long as unsuccessful calls return a falsy value:
var element = findElement() || findSomeOtherElement() || makeALastAttempt();
jQuery selectors are, however, truthy even when they are empty.
Is there an elegant way if saying "I want the element at this selector, and if it does not exist, then the element at that selector"?
- possible duplicate of jQuery equivalent of || or ?? operator – Brock Adams Commented Jun 20, 2014 at 3:11
6 Answers
Reset to default 6If you expect only one element you can do this:
var element = $(findElement()[0] || findSomeOtherElement()[0] || makeALastAttempt()[0]);
Why not using:
jQuery.fn.exists = function(){
if(this.length>0)
return this;
return false; };
var a = ($(selector1).exists() || $(selector2).exists());
Will select an element with name anchorName
and if not found select another element with ID #anchorName
$("[name=anchorName], #anchorName").first()
If you're only wanting a single element as your result, I ended up with:
$('#preferred-element').add($('#fallback-element')).first();
No. Sorry, you'll have to use the .length
property. This is a side effect of Javascript evaluating all objects as truthy, and obviously a jQuery selector is functionally an object. However, the resulting syntax is not so bad:
$(function(){
var element = $('.findElement'),
otherElement = $('.findSomeOtherElement'),
lastAttempt = $('.lastAttempt');
var elegance = (element.length && element)
|| (otherElement.length && otherElement)
|| (lastAttempt.length && lastAttempt);
elegance.css('border','1px solid green');
});
DEMO
Heres an answer a lot closer to what was actually desired.
var fallback = function(options){
var numOfOptions = options.length;
if (numOfOptions == 2){
return (options[0].length > 0)? options[0] : options[1];
}else if (numOfOptions > 2){
return fallback(options.slice(1));
}else if (numOfOptions == 1){
return options[0];
}else{
return $();
}
};
fallback([$(selector1),$(selector2),$(selector3)]);
本文标签: javascriptFind fallback element in jQueryStack Overflow
版权声明:本文标题:javascript - Find fallback element in jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741620162a2388761.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论