[英]javascript ternary operator to increase or subtract value
The only difference in the following code are the - and + symbols used to increase or subtract the value. 以下代码中的唯一区别是用于增加或减少该值的-和+符号。
if( that.hasClass('prev') ){
$('.elem').scrollLeft( $('.elem').scrollLeft()-(0.1*factor) );
}
else if( that.hasClass('next') ){
$('.elem').scrollLeft( $('.elem').scrollLeft()+(0.1*factor) );
}
I would like to know how to convert the code in a small ternary statement, is it possible? 我想知道如何在一个小的三元语句中转换代码,这可能吗?
If you really need to test both classes ("next" and "prev"), you can factor out the logic: 如果确实需要测试两个类(“ next”和“ prev”),则可以考虑逻辑:
var mul = that.hasClass("prev") ? -1 :
that.hasClass("next") ? 1 :
0;
$(".elem").scrollLeft($(".elem").scrollLeft() + mul * 0.1 * factor);
You could turn that into a jQuery function if you felt particularly energetic: 如果您感到特别精力充沛,可以将其转换为jQuery函数:
$.fn.scrollDir = function() {
return that.hasClass("prev") ? -1 :
that.hasClass("next") ? 1 :
0;
};
$(".elem").scrollLeft($(".elem").scrollLeft() + that.scrollDir() * 0.1 * factor);
If you really want to do this the following should work: 如果您确实要执行此操作,则应执行以下操作:
$('.elem').scrollLeft($('.elem').scrollLeft()+(0.1*factor*(that.hasClass('prev') ? -1 : that.hasClass('next') ? 1 : 0)))
But for clarity, I'd probably leave it as you have written. 但是为了清楚起见,我可能会保留您所写的内容。
我会这样做
(that.hasClass('prev')) ? $('.elem').scrollLeft( $('.elem').scrollLeft()-(0.1*factor) ) : $('.elem').scrollLeft( $('.elem').scrollLeft()+(0.1*factor) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.