Javascript 如何在jQuery中编写三元运算符条件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6595585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:24:52  来源:igfitidea点击:

How to write ternary operator condition in jQuery?

javascriptjqueryternary

提问by Leahcim

In this fiddle http://jsfiddle.net/mjmitche/6nar4/3/, if you drag, for example, the little blue box into the yellow box, then the big black box will turn pink. All of the 4 boxes along the left can be dragged into the boxes inside the black box.

在这个小提琴http://jsfiddle.net/mjmitche/6nar4/3/ 中,例如,如果将蓝色小框拖入黄色框,则黑色大框将变为粉红色。左边的所有 4 个框都可以拖动到黑框内的框内。

At the end of the fiddle, you see the code that changes the black box to pink.

在小提琴的末尾,您会看到将黑框更改为粉红色的代码。

However, I want to make that a ternary operator, so that if the box is black, then it turns pink, but if it's been turned pink, then I want it to go back to black.

但是,我想把它变成一个三元运算符,这样如果盒子是黑色的,那么它就会变成粉红色,但如果它变成粉红色,那么我希望它变回黑色。

I know the ternary is like this

我知道三元是这样的

x ? y: z

So I tried this, even though I knew it wasn't probably right

所以我尝试了这个,即使我知道这可能不对

$("#blackbox").css({'background':'pink'}); ?

    $("#blackbox").css({'background':'black'}); : 

$("#blackbox").css({'background':'pink'}); 

I think the first line before the question mark is causing the problem, so how to create the ifstatement?

我认为问号前的第一行是导致问题的原因,那么如何创建if语句?

回答by Shadow Wizard is Ear For You

I would go with such code:

我会使用这样的代码:

var oBox = $("#blackbox");
var curClass = oBox.attr("class");
var newClass = (curClass == "bg_black") ? "bg_pink" : "bg_black";
oBox.removeClass().addClass(newClass);

To have it working, you first have to change your CSS and remove the backgroundfrom the #blackboxdeclaration, add those two classes:

要让它工作,你首先必须改变你的 CSS 并background#blackbox声明中删除,添加这两个类:

.bg_black { background-color: #000; }
.bg_pink { background-color: pink; }

And assign the class bg_blackto the blackboxelement initially.

并分配类bg_blackblackbox最初的元素。

Updated jsFiddle: http://jsfiddle.net/6nar4/17/

更新 jsFiddle:http: //jsfiddle.net/6nar4/17/

In my opinion it's more readable than the other answers but it's up to you to choose of course.

在我看来,它比其他答案更具可读性,但当然由您来选择。

回答by RobG

I think Dan and Nicola have suitable corrected code, however you may not be clear on why the original code didn't work.

我认为 Dan 和 Nicola 有合适的更正代码,但是您可能不清楚为什么原始代码不起作用。

What has been called here a "ternary operator" is called a conditional operator in ECMA-262 section 11.12. It has the form:

此处称为“三元运算符”的内容在 ECMA-262 第 11.12 节中称为条件运算符。它具有以下形式:

LogicalORExpression ? AssignmentExpression : AssignmentExpression

The LogicalORExpression is evaluated and the returned value converted to Boolean (just like an expression in an if condition). If it evaluates to true, then the first AssignmentExpression is evaluated and the returned value returned, otherwise the second is evaluated and returned.

计算 LogicalORExpression 并将返回值转换为布尔值(就像 if 条件中的表达式一样)。如果计算结果为真,则计算第一个 AssignmentExpression 并返回返回值,否则计算并返回第二个。

The error in the original code is the extra semi-colons that change the attempted conditional operator into a series of statements with syntax errors.

原始代码中的错误是额外的分号将尝试的条件运算符更改为一系列具有语法错误的语句。

回答by Nicola Peluchetti

I'd do (added caching):

我会做(添加缓存):

var bbx = $("#blackbox");
 bbx.css('background-color') === 'rgb(255, 192, 203)' ? bbx.css('background','black') : bbx.css('background','pink')

wroking fiddle (new AGAIN): http://jsfiddle.net/6nar4/37/

工作小提琴(再次新):http: //jsfiddle.net/6nar4/37/

I had to change the first operator as css()returns the rgb value of the color

我不得不更改第一个运算符作为css()返回颜色的 rgb 值

回答by Chris

The Ternary operator is just written as a boolean expression followed by a questionmark and then two further expressions separated by a colon.

三元运算符只是写成一个布尔表达式,后跟一个问号,然后是两个由冒号分隔的其他表达式。

The first thing that I can see that you have got wrong is that your first expression isn't returning a boolean or anything sensible that could be converted to a boolean. Your first expression is always going to return a jQuery object that has no sensible interpretation as a boolean and what it does convert to is probably an unchanging interpretation. You are always best off returning something that has a well known boolean interpretation, if nothign else for the sake of readability.

我能看到的第一件事是你错了,你的第一个表达式没有返回布尔值或任何可以转换为布尔值的合理值。您的第一个表达式总是会返回一个 jQuery 对象,该对象没有作为布尔值的合理解释,并且它确实转换为可能是不变的解释。如果不是为了可读性,你总是最好返回具有众所周知的布尔解释的东西。

The second thing is that you are putting a semicolon after each of your expressions which is wrong. In effect this is saying "end of construct" and so is breaking your ternary operator.

第二件事是你在每个错误的表达式后面都放了一个分号。实际上,这是在说“构造结束”,因此破坏了您的三元运算符。

In this situation though you probably can do this a more easy way. If you use classes and the toggleClass method then you can easily get it to switch a class on and off and then you can put your styles in that class definition (Kudos to @yoavmatchulsky for suggesting use of classes up there in comments).

在这种情况下,虽然您可能可以通过更简单的方式做到这一点。如果您使用类和 toggleClass 方法,那么您可以轻松地使用它来打开和关闭类,然后您可以将样式放入该类定义中(感谢@yoavmatchulsky 在评论中建议使用类)。

A fiddle of this is found here: http://jsfiddle.net/chrisvenus/wSMnV/(based on the original)

这里有一个小提琴:http: //jsfiddle.net/chrisvenus/wSMnV/(基于原始)

回答by Dan

From what it looks like you are trying to do, togglemight better solve your problem.

从看起来您正在尝试做的事情来看,切换可能会更好地解决您的问题。

EDIT: Sorry, toggle is just visibility, I don't think it will help your bg color toggling.

编辑:抱歉,切换只是可见性,我认为它不会帮助您切换背景颜色。

But here you go:

但是你去吧:

var box = $("#blackbox");
box.css('background') == 'pink' ? box.css({'background':'black'}) : box.css({'background':'pink'}); 

回答by Saeed Neamati

Ternary operator works because the first part of it returns a Boolean value. In your case, jQuery's css method returns the jQuery object, thus not valid for ternary operation.

三元运算符有效,因为它的第一部分返回一个布尔值。在您的情况下,jQuery 的 css 方法返回 jQuery 对象,因此对三元运算无效。

回答by Karoly Horvath

Also, the ternary operator expects expressions, not statements. Do not use semicolons, only at the end of the ternary op.

此外,三元运算符需要表达式,而不是语句。不要使用分号,只在三元运算的末尾使用。

$("#blackbox").css({'background': 
    $("#blackbox").css('background') === 'pink' ? 'black' : 'pink'});

回答by andyb

As others have correctly pointed out, the first part of the ternary needs to return trueor falseand in your question the return value is a jQuery object.

正如其他人正确指出的那样,三元组的第一部分需要返回truefalse在您的问题中返回值是一个 jQuery 对象。

The problem that you may have in the comparison is that the web colorwill be converted to RGB so you have to text for that in the ternary condition.

您在比较中可能遇到的问题是Web 颜色将转换为 RGB,因此您必须在三元条件下为该颜色添加文本。

So with the CSS:

所以使用 CSS:

#blackbox {
    background:pink;
    width:10px;
    height:10px;
}

The following jQuery will flip the colour:

以下 jQuery 将翻转颜色:

var b = $('#blackbox');
b.css('background', (b.css('backgroundColor') === 'rgb(255, 192, 203)' ? 'black' : 'pink'));

Demo

演示

回答by Sergio Rodriguez

Here is a working example in side a function:

这是一个函数中的工作示例:

function setCurrency(){
   var returnCurrent;
   $("#RequestCurrencyType").is(":checked") === true ? returnCurrent = 'Dollar': returnCurrent = 'Euro';
   
   return returnCurrent;
}

In your case. Change the selector and the return values

在你的情况下。更改选择器和返回值

$("#blackbox").css('background-color') === 'pink' ? return "black" : return "pink";

lastly, to know what is the value used by the browser run the following in the console:

最后,要知道浏览器使用的值是什么,请在控制台中运行以下命令:

$("#blackbox").css('background-color')

and use the "rgb(xxx.xxx.xxx)" value instead of the Hex for the color selection.

并使用“rgb(xxx.xxx.xxx)”值代替十六进制进行颜色选择。