开发者

Writing an if/then statement in jQuery

How do I write a selector so that it says

var myDefault;
if $('th.default') {
   myDefault = $('th.default');
} else {
   myDefault = $('th:eq(2)'); // 3rd column
}

It probably uses something like:

var myDefault = $('th.default') || $('th:eq(2)');

except the first selection is not returning falsey if there is no th with a class="de开发者_开发问答fault".


var myDefault = $('th.default').length ? $('th.default') : $('th:eq(2)');

Or, if you LOVE caching :) :

var defaultElement = $('th.default');
var myDefault = defaultElement.length ? defaultElement : $('th:eq(2)');


var myDefault = $('th.default');
if (!myDefault.length) { myDefault = $('th:eq(2)'); }


var myDefault;
if ($('th.default').length) {
   myDefault = $('th.default');
} else {
   myDefault = $('th:eq(2)'); // 3rd column
}


$('th.default') will return a jQuery object, so it will never be false.

You can use array notation to check the element: $('th.default')[0] will return true if elements were matched (and will contain the first matched element) or will return false if there are no matched elements.

You can test and set myDefault with a ternary operator:

var myDefault = $('th.default')[0] ? $('th.default') : $('th:eq(1)');

Here's a working demo. Just remove class="default" to switch between the two.


You need to use

if $('th.default').length {}

Your conditional returns true, as all objects are true. Your object could be an empty jQuery selector, but this would still return true. If your selector has no matches, length returns "0", which is falsy.

Edit: I had this as a method... should have been a property!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜