【问题标题】:disable enable button using jquery使用 jquery 禁用启用按钮
【发布时间】:2016-02-05 00:13:46
【问题描述】:

我有一个可用的 javascript 版本来禁用/启用一个 from 按钮,但我无法使用 jQuery 让它工作。

我的 jsfiddle 有两个版本。 javascript版本被注释掉了。

    //NOT WORKING jQuery
   function controls(id) {
   if (id === "button_start") {
    //$('button_start').prop('disabled','disabled');
    // $('button_stop').removeProp('disabled','disabled');

    // testing
    $('#button_start').on('click',function() {
        $(this).prop('disabled', 'disabled');
    });
    $('#button_stop').on('click', function(){
        $(this).removeProp('disabled', 'disabled');
    });

    //console.log(id);

   } else {
    //$('button_stop').prop('disabled','disabled');
    //$('button_start').removeProp('disabled','disabled');

     // testing
    $('#button_stop').click(function() {
        $(this).prop('disabled', 'disabled');
    });
    $('#button_start').click(function(){
        $(this).removeProp('disabled', 'disabled');
    });
      //console.log(id);
        }
    }

jsFiddle:https://jsfiddle.net/tommy6s/w2u8eskv/

感谢您的帮助!

【问题讨论】:

  • 禁用的属性是一个布尔值。设置为真或假,不要设置为字符串或尝试删除。
  • 如果您将工作中的 JavaScript 从小提琴复制到问题中,这个问题会更容易理解。

标签: javascript jquery html css


【解决方案1】:

这可能无法解决您的问题,但是您使用的removeProp 方法错误。根据 jQuery 文档,removeProp 只有一个属性

.removeProp( propertyName )
propertyName
Type: String
The name of the property to remove.

在你的例子中,我会改变你的线条,看起来像这样

$('#button_start').click(function(){
    $(this).removeProp('disabled', 'disabled');
});

到这里

$('#button_start').click(function(){
    $(this).removeProp('disabled');
});

https://api.jquery.com/removeProp/

另外,请记住 id 元素必须以 # 符号开头。你在你的 OP 中有这个,但在小提琴中没有。

【讨论】:

    【解决方案2】:

    您的选择器错误。

    $('button_start')
    

    应该是

    $('#button_start') 
       ^--------------- Missing id selector syntax
    

    然后你需要包含 jQuery 库才能让 fiddle 开始工作。

    【讨论】:

      【解决方案3】:

      添加样式:

      #button_start:disabled{background:blue;opacity:0.3;}
      

      和你的脚本:

      function controls(id) {
      
          if (id === "button_start") {
              $('#button_start').attr('disabled','disabled');      
              $('#button_stop').removeProp('disabled');
          } else {
              $('#button_stop').attr('disabled','disabled');
              $('#button_start').removeProp('disabled');
          }
      }
      

      【讨论】:

        【解决方案4】:

        对于 1.6 之后的 jQuery 版本:

        $('#button_start').prop('disabled', false); //to enable and pass true to disable
        

        对于其他选项和版本,请查看此 SO 答案Disabling and enabling an HTML input button

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-02
          • 2010-12-08
          • 1970-01-01
          相关资源
          最近更新 更多