使用三元运算符缩短代码 [英] Shorten code using Ternary Operators

查看:108
本文介绍了使用三元运算符缩短代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用三元运算符缩短以下内容?

How would one shorten the following using ternary operators?

if ((pos - maxPos) == (c.clientWidth)) {
    $j("#next").addClass("filter");
} else {
    $j("#next").removeClass("filter");
}


推荐答案

无需使用三元运营商, .toggleClass() 接受一秒钟确定是否应该添加或删除类的参数:

No need to use a ternary operator, .toggleClass() accepts a second argument to determine if the class should be added or removed:

$j('#next').toggleClass('filter', ((pos - maxPos) == c.clientWidth))

然而,为了回答你的问题与你提出的问题完全一样(不要使用它!):

However, for the sake of answering your question exactly like you asked (don't use it!):

$j('#next')[((pos - maxPos) == c.clientWidth) ? 'addClass' : 'removeClass']('filter');

这篇关于使用三元运算符缩短代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆