How to write ternary operator condition in jQuery?

后端 未结 9 1468
眼角桃花
眼角桃花 2020-12-29 19:41

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

相关标签:
9条回答
  • 2020-12-29 20:09

    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.

    0 讨论(0)
  • 2020-12-29 20:11

    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 background from the #blackbox declaration, add those two classes:

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

    And assign the class bg_black to the blackbox element initially.

    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.

    0 讨论(0)
  • 2020-12-29 20:13

    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.

    0 讨论(0)
提交回复
热议问题