最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript Shorthand for a jQuery If-Else Snippet - Stack Overflow

programmeradmin0浏览0评论

I have this snippet of code:

<script type="text/javascript">
$(window).load(function() {
    if(!$.browser.msie){ 
        $('#myDiv').animate({opacity: 1}, 300);
    } else if ($.browser.msie) {
        $('#myDiv').css({opacity:1});
    }
}); 
</script>

How can I say the same thing using the " : something ? somethingElse " syntax?

Thanks in advance?

I have this snippet of code:

<script type="text/javascript">
$(window).load(function() {
    if(!$.browser.msie){ 
        $('#myDiv').animate({opacity: 1}, 300);
    } else if ($.browser.msie) {
        $('#myDiv').css({opacity:1});
    }
}); 
</script>

How can I say the same thing using the " : something ? somethingElse " syntax?

Thanks in advance?

Share Improve this question asked Feb 12, 2013 at 14:55 Dimitri VorontzovDimitri Vorontzov 8,11412 gold badges51 silver badges78 bronze badges 4
  • 4 Don't use ternary operators as a generic if/else. Use them for simple assignments, that is what they are designed for. Real if/else across more lines are more readable. Embrace readability over code golf. – Quentin Commented Feb 12, 2013 at 14:57
  • 2 The long and short of it is you probably don't want to. Nested ternary syntax gets very ugly. – David Kiger Commented Feb 12, 2013 at 14:57
  • 2 ... also the else if ($.browser.msie) { is redundant. A simple else { would be enough. – Yoshi Commented Feb 12, 2013 at 14:57
  • I agree with you 100%, guys, but in this case I actually do need the "code golf", for a certain reason. – Dimitri Vorontzov Commented Feb 12, 2013 at 14:58
Add a ment  | 

2 Answers 2

Reset to default 7

Not sure I got the question, however:

$.browser.msie ? $('#myDiv').css({opacity: 1}) : $('#myDiv').animate({opacity: 1}, 300);

Also, I'm not an expert of IE anymore, but I wonder if you could do something like:

$('#myDiv').animate({opacity: 1}, $.browser.msie ? 0 : 300);

That should be applied immediately, and made it more readable with an external variable:

var speed = $.browser.msie ? 0 : 300;
$('#myDiv').animate({opacity: 1}, speed);

Or something like that.

You can do it like this:

$(window).load(function() {
    $.browser.msie ? $('#myDiv').css({opacity:1}); : $('#myDiv').animate({opacity: 1}, 300);
});

I wouldn't remend it for at least two reasons (browser sniffing, and readability), but you can.

Another way:

$(window).load(function() {
    $('#myDiv')[$.browser.msie ? 'css' : 'animate']({opacity:1}, $.browser.msie ? undefined : 300);
});

...but that's even worse. ;-)

发布评论

评论列表(0)

  1. 暂无评论