[英]how to shorten jquery syntax if-else statement?
I'm using a lot of these: 我正在使用很多这些:
$text = $menu.jqmData('menu-text') ?
$menu.jqmData('menu-text') : self.options.menuTxt;
It already is the "shorthand" syntax, but I'm wondering, whether it's possible to reduce the above line even further. 它已经是“简写”语法,但是我想知道是否有可能进一步减少上述行。 There must be a better way than checking for $menu.jqmData('menu-text') and then writing the whole thing again. 必须有一种更好的方法,而不是先检查$ menu.jqmData('menu-text') ,然后重新编写整个内容。 Isn't there? 不在吗
Thanks for help! 感谢帮助!
A shorter way is to use the double pipe. 一种较短的方法是使用双管。 It basically uses the second value if the first is falsy
. 如果第一个值是falsy
,则基本上使用第二个值。
$text = $menu.jqmData('menu-text') || self.options.menuTxt;
You can also use it multiple time in the same line. 您也可以在同一行中多次使用它。 Let's say you had a variable uberMenuTxt
which takes priority over the other two and you could do it like so. 假设您有一个变量uberMenuTxt
,它比其他两个优先级高,您可以这样做。
$text = uberMenuTxt || $menu.jqmData('menu-text') || self.options.menuTxt;
It basically keeps on going every time the current value is falsy
and will stop at the first that is not. 基本上,每次当前值是falsy
,它都会继续运行,并且会在第一个不是的情况下停止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.