简体   繁体   中英

Can I put IF statements in a switch case function?

it's me again :) Some helpful members helped me get a script working, but I ran into a brick wall with a case that I also want to have an IF statement. It looks like this:

$(document).ready(function() {
    $("input[type='button']").click(function() {
      switch(this.id) {
        case:'buttonone':
              if( $('#one').attr('readonly')) {

                $("#changeone").attr('value', 'Save');
                $('#one').attr('readonly', false);
                $('#one').addClass('focusField');
                $("#questiononetext").html("When do you want to go out?");

} else {

                $("#changeone").attr('value', 'Change');
                $('#one').attr('readonly', true);
                $('#one').removeClass('focusField');
                $("#questiononetext").html("Date: ");

} break;
        case 'buttontwo': $("#questiononetext").html("Content changed"); break;
        case 'buttonthree': $("#content").html("Content changed again"); break;
      }
    });
});

Notice what comes after CASE: buttonone, I tried an if statement and that broke the whole script. Does anyone have any ideas as to why this happens? Thank you :)))

Your switch statement is redundant, the only reason it's there is you're using the same click handler for multiple buttons, but they share nothing in common.

Instead you should have 3 click handlers:

$('#buttonone').click(function(){
  ...
});

$('#buttontwo').click(function(){
  ...
});

$('#buttonthree').click(function(){
  ...
});

And the if statement in buttonone's handler is totally legitimate.

Not sure is it the extra colon after the "case" in "case: buttonone". Please check

I think IF within CASE has no problem. problem may be $('#one').attr('readonly') . use can use data property here. I test that $('#one').attr('readonly') is not working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM