开发者

Shorten JQuery Snippet

开发者 https://www.devze.com 2023-01-17 08:12 出处:网络
I have the following JQ开发者_高级运维uery snippet: (someVar.next().length == 0)?someVar.fadeOut().end().find(\"ul\").first().fadeIn():someVar.fadeOut().next().fadeIn();

I have the following JQ开发者_高级运维uery snippet:

(someVar.next().length == 0)?someVar.fadeOut().end().find("ul").first().fadeIn():someVar.fadeOut().next().fadeIn();

There is a fair amount of code duplication between the two results of the conditional - i.e. someVar.fadeOut() and .fadeIn() on both.

I would ideally like something like this:

someVar.fadeOut().((someVar.next().length == 0)?end().find("ul").first():next()).fadeIn();

But that doesn't work :) Safari developer tools reports a syntax error but I'm not skilled enough to work out how to do it properly.

If it can't be shortened, then just saying that is fine :)


I removed the .end() because I don't see a use for it.

Otherwise, I just moved .fadeOut() into the conditional test.

(someVar.fadeOut().next().length == 0) 
?  someVar.end().find("ul:first").fadeIn()
:  someVar.next().fadeIn();

Or maybe this?

var $in = (someVar.fadeOut().next().length == 0) 
           ? someVar.end().find("ul:first")
           : someVar.next();
$in.fadeIn();

EDIT: As noted by @T.J. Crowder, I was not correct in removing .end(). I didn't realize that it continues to work if you start a new chain with the previous result. Makes sense though. Fixed.

Also, I had somehow reversed the second example. Fixed.


Another EDIT:

The second example could be further simplified like this:

((someVar.fadeOut().next().length == 0) 
           ? someVar.end().find("ul:first")
           : someVar.next()).fadeIn();

One more EDIT:

Another possibility is to simply .fadeIn() the .next() either way, which will have no effect if its length is 0:

if(someVar.fadeOut().next().fadeIn().length == 0)
     someVar.end().find("ul:first").fadeIn();


Not by much, no — or at least, not in a reasonable way (there are games you can play with strings and bracketed notation, but they would make your example worse, not better). You could move the fadeOut to its own statement:

someVar.fadeOut();
(someVar.next().length == 0)?someVar.end().find("ul").first().fadeIn():someVar.next().fadeIn();

...but after that, the chaining goes in different directions.

See also my community wiki answer.


Perhaps somewhat off-topic and so I'm making it a CW, but: When things get long like this, can I just put in my bid for good old-fashioned if/else statements?

someVar.fadeOut();
if (someVar.next().length === 0) {
    someVar.end().find("ul").first().fadeIn();
}
else {
    someVar.next().fadeIn();
}

About eight times easier to read and maintain, IMHO.

0

精彩评论

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