开发者

this || that || whatever style syntax in jQuery

I've got jQuery code that looks like this:

var $selected = $('#mySelector');

if (!$selected.length) {
  $开发者_StackOverflow社区selected = $('#anotherSelector');

  if (!$selected.length) {
    // etc.
  }
}

Pretty ugly. I'd like to do something like this:

var $selected = $('#mySelector') || $('#anotherSelector') || etc.

But since jQuery returns a jQuery object even when a selector doesn't match, this syntax doesn't work. Is there an equivalent with jQuery objects (or maybe a selector)? Thanks!


Not sure if this is the best approach but you could write out a small function to help achieve this. Live Example

HTML

<div class="asdf">ad</div>
<div class="asdf">ad</div>
<div class="asdf">ad</div>
<div class="asdf">ad</div>
<div class="asdf">ad</div>

JS

function test(selector){
    var list = $(selector);
    if (list.length > 0) return list;
    else return null;
}

console.log($('.asdfasdf') || $('.asdf'));
console.log(test('.asdfasdf') || test('.asdf'));


You could (ab)use the comma operator:

var $selected;
($selected = $('#mySelector'), $selected.length) ||
  ($selected = $('#anotherSelector'), $selected.length);


As an extension to my question, if you know you only ever want the first matching element (assuming that there's a possibility that both will exist) you can do something like this:

var $selected = $('#mySelector, #altSelector').slice(0,1);

That's going to limit the return result to only one element, which will be the first selector if present, the second if the first is missing and the second isn't, or an empty object if both are missing from the page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜