【问题标题】:Remove disabled attribute with jquery not working in Chrome删除禁用的属性与 jquery 在 Chrome 中不起作用
【发布时间】:2014-01-26 22:08:30
【问题描述】:

我正在尝试将禁用属性删除/添加到 ID 为“注册”的按钮。这是我尝试过的代码,但它不起作用..

$(document).ready(function() {

 $('.tos').click(function(){
    var isChecked = $('.tos').is(':checked');
    if(isChecked)
      console.log("True");
      $('#register').removeAttr("disabled");
    else
      console.log("False");

  });

});

我在控制台中收到此错误,但我不知道这是什么意思。

Uncaught SyntaxError: Unexpected token else 

这是我要删除/添加禁用属性的按钮。

<button type="submit" id="register" name="register" class="btn btn-block btn-color btn-xxl" disabled>Create an account</button>

任何帮助将不胜感激!

【问题讨论】:

  • 如果你想在条件为true的情况下运行多个语句,你必须将它们放在一个块{...}中。否则读取为jsfiddle.net/5bgH9,这显然是无效的。正如您在MDN documentation 中所读到的那样,要在一个子句中执行多个语句,请使用块语句 ({ ... }) 对这些语句进行分组。通常,始终使用块语句是一种好习惯,尤其是在涉及嵌套if 语句的代码中:"

标签: javascript jquery button attributes prop


【解决方案1】:

Uncaught SyntaxError: Unexpected token else

这是因为您没有在 if 语句中使用 {} 语法。不使用它们很好,但只有当你有 one 行要执行时。在这种情况下,你的 else 是第二行,它打破了“只有一行没有大括号”的规则。

使用大括号:

if(isChecked) {
      console.log("True");
      $('#register').removeAttr("disabled");
} else
     console.log("False");

【讨论】:

    【解决方案2】:

    第一个 if 主体周围没有大括号。应该是:

    如果(已检查){ console.log("真"); $('#register').removeAttr("disabled"); } 别的 { console.log("假"); }

    从技术上讲,第二组大括号是可选的,但值得使用

    【讨论】:

      【解决方案3】:
      if(isChecked)
        console.log("True");
        $('#register').removeAttr("disabled");
      else
        console.log("False");
      

      那是什么?


      if(isChecked){
        console.log("True");
        $('#register').removeAttr("disabled");
      }else{
        console.log("False");
      }
      

      现在这就是你正确的做法;)

      【讨论】:

        【解决方案4】:

        对于if else 语句,您可以使用以下两种语法之一:

        //either....
        if (condition)
            one_action();
        else
            one_other_action();
        //or....
        if (condition) {
            one_action()
            more_actions()
        } else {
            one_other_action();
            and_some_more();
        }
        

        因此,当条件为真时在块包含单个操作时,您可以省略要执行的操作块周围的{}。由于您正在执行 console.log jQuery 函数,if else 语句被中断,JavaScript 不再识别您在其中。因此,它不会看到else 的到来。要完成这项工作,只需将 {} 放在它周围,就像其他答案显示的那样。

        【讨论】:

          【解决方案5】:

          别忘了{...}

          $('.tos').click(function(){
              var isChecked = $('.tos').is(':checked');
              if(isChecked){
                console.log("True");
                $('#register').removeAttr("disabled");
              } else {
                console.log("False");
              }
            });
          

          【讨论】:

            猜你喜欢
            • 2019-01-02
            • 1970-01-01
            • 2018-02-04
            • 1970-01-01
            • 2018-02-28
            • 2012-11-17
            • 2016-08-11
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多