首页 文章

切换按钮时从表单域中删除禁用的属性

提问于
浏览
1

当我切换按钮(打开)时,我试图删除禁用的属性,反之亦然 .

此时我只创建了一个click事件来删除已禁用的attr .

HTML是:输入:

<input id="wb_owner_field" type="text" disabled value="" placeholder="" class="form-control">

关闭时的开/关切换它具有类: switch-off 并且当它上面有类 switch-on

<div id="wb_owner_toggle" class="switch-off switch-animate" style="">
  <input type="checkbox" data-toggle="switch">
  <span class="switch-left"></span><label>&nbsp;</label>
  <span class="switch-right"></span>
</div>

直到现在使用的代码 .

$("#wb_owner_toggle").click(function(){
      $('#wb_owner_field').prop("disabled", false);
});

基本上我需要在切换div类更改时启动,并根据类删除或添加字段上的禁用attr .

3 回答

  • 0

    干得好

    $("#wb_owner_toggle").click(function(){
          var owner_el = $('#wb_owner_field');
          owner_el.attr('disabled', !owner_el.is(':disabled'));
    });
    
  • 1

    使用hasClass()

    $("#wb_owner_toggle").click(function(){
          if($(this).hasClass('switch-off')){
                $('#wb_owner_field').prop("disabled", false);
          }
    });
    
  • 1

    正确的答案是 disabled 属性是 boolean attribute .

    元素上存在布尔属性表示真值,缺少属性表示false值 . http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes

    请仔细阅读 . 假值 - 缺少该属性 .

    disabled="false" 完全错误 .

    所以,通过jQuery删除它的正确方法是:

    element.removeAttr('disabled');

    如果此算法确认您的情况,代码将是:

    $("#wb_owner_toggle").click(function() {
      if ($(this).hasClass('switch-off')) {
        $('#wb_owner_field').removeAttr('disabled');
      }
      else {
        $('#wb_owner_field').attr('disabled');
      }
    });
    

相关问题