11
the_styles ? the_styles.appendTo('head'); the_styles=null : the_styles = $('.stylesheet').detach();

显然,这是无效的。注意“;” appendTo()和之间the_styles=null。我如何将它写在 1 行并且仍然有多个这样的表达式?

4

6 回答 6

21

以这种方式使用逗号运算符:

the_styles ? (the_styles.appendTo('head'), the_styles=null) : the_styles =  $('.stylesheet').detach();

以下是 Mozilla 开发人员中心对逗号运算符的描述:

当您想在需要单个表达式的位置包含多个表达式时,可以使用逗号运算符。此运算符最常见的用法是在 for 循环中提供多个参数。

在此处阅读更多信息:https ://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Comma_Operator

于 2010-07-02T18:32:55.657 回答
8

谁需要三元运算符?

​the_styles = !the_styles && $('.stylesheet').detach()​​​​ ||
             the_styles.appendTo('head') && null;​

必须切换表达式,否则null第一个表达式的值将始终强制计算第二个表达式.detach()

聪明的代码唯一的一点是,一旦你在喝咖啡休息后回到它,它甚至对你来说都没有任何意义。所以这要好得多:

if(the_styles) {
    the_styles.appendTo('head')
    the_styles = null;
}
else {
    the_styles = the_styles.detach('.stylesheet');
}

对我来说,即使是上述简单化的版本也没有任何意义。什么部分很明显,但为什么要这样做

于 2010-07-02T18:41:07.763 回答
2
the_styles ? (function() {the_styles.appendTo('head'); the_styles=null})() : <etc>

只需将代码块包装在(function() { and中即可})()

现在是困难的部分:你为什么要这样做?也许有更好的解决方案!

于 2010-07-02T18:18:06.127 回答
1

我同意光晕编码器,但如果你仍然想要它:

the_styles ? function(){ the_styles.appendTo('head'); the_styles=null;}() : the_styles = $('.stylesheet').detach();
于 2010-07-02T18:19:07.433 回答
0
the_styles ? the_styles.appendTo('head') : the_styles = $('.stylesheet').detach();

如果您覆盖它,您不需要将其设为空!

于 2010-07-02T18:19:25.793 回答
0
the_styles=the_styles || $('.stylesheet').detach(); the_styles.appendTo('head');
于 2010-07-02T18:19:51.597 回答