开发者

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 :)开发者_Python百科))


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜