如何在jQuery中编写三元运算符条件? [英] How to write ternary operator condition in jQuery?

查看:430
本文介绍了如何在jQuery中编写三元运算符条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个小提琴中 http://jsfiddle.net/mjmitche/6nar4/3/ 如果你把小蓝盒子拖到黄色的盒子里,那么大的黑盒子会变成粉红色。左侧的所有4个方框都可以拖入黑匣子内的方框中。

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.

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

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.

我知道三元是这样的

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

我认为问号前面的第一行是导致问题的,所以如何创建 if 声明?

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

推荐答案

我会使用这样的代码:

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

要让它正常工作,首先必须更改CSS并删除后台来自 #blackbox 声明,添加这两个类:

To have it working, you first have to change your CSS and remove the background from the #blackbox declaration, add those two classes:

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

并将类 bg_black 分配给最初 blackbox 元素。

And assign the class bg_black to the blackbox element initially.

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

Updated 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.

这篇关于如何在jQuery中编写三元运算符条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆