Shorten code using Ternary Operators

自作多情 提交于 2019-12-08 12:04:20

问题


How would one shorten the following using ternary operators?

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

回答1:


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');



回答2:


Even better than a ternary, using the switch param in toggleClass()

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


来源:https://stackoverflow.com/questions/11132105/shorten-code-using-ternary-operators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!