使用jQuery切换input禁用的属性

这是我的代码:

$("#product1 :checkbox").click(function(){ $(this) .closest('tr') // Find the parent row. .find(":input[type='text']") // Find text elements in that row. .attr('disabled',false).toggleClass('disabled') // Enable them. .end() // Go back to the row. .siblings() // Get its siblings .find(":input[type='text']") // Find text elements in those rows. .attr('disabled',true).removeClass('disabled'); // Disable them. }); 

如何切换.attr('disabled',false);

我似乎无法在Google上find它。

 $('#el').prop('disabled', function(i, v) { return !v; }); 

.prop()方法接受两个参数:

  • 属性名称 (禁用,选中,选中)任何真或假
  • 属性 ,可以是:
    • ) – 返回当前值。
    • 布尔值 (true / false) – 设置属性值。
    • 函数 – 为每个find的元素执行,返回的值用于设置属性。 有两个参数通过; 第一个参数是索引 (0,1,2,每个find的元素增加)。 第二个参数是元素的当前 (true / false)。

所以在这种情况下,我使用了一个函数,它为我提供了索引(i)和当前值(v),然后我返回了与当前值相反的值,所以属性状态相反。

获得完整的浏览器可比性disabled应设置的值disabled或被删除!
这是我刚才制作的一个小插件:

 (function($) { $.fn.toggleDisabled = function() { return this.each(function() { var $this = $(this); if ($this.attr('disabled')) $this.removeAttr('disabled'); else $this.attr('disabled', 'disabled'); }); }; })(jQuery); 

示例链接 。

编辑:更新了示例链接/代码来维护链接性!
编辑2:
根据@lonesomeday评论,这是一个增强版本:

 (function($) { $.fn.toggleDisabled = function(){ return this.each(function(){ this.disabled = !this.disabled; }); }; })(jQuery); 

     $( '#checkbox')。点击(函数(){
         $('#submit')。attr('disabled',!$(this).attr('checked'));
     });

这对于attr的callback语法来说非常简单:

 $("#product1 :checkbox").click(function(){ $(this) .closest('tr') // find the parent row .find(":input[type='text']") // find text elements in that row .attr('disabled',function(idx, oldAttr) { return !oldAttr; // invert disabled value }) .toggleClass('disabled') // enable them .end() // go back to the row .siblings() // get its siblings .find(":input[type='text']") // find text elements in those rows .attr('disabled',function(idx, oldAttr) { return !oldAttr; // invert disabled value }) .removeClass('disabled'); // disable them }); 

不久之后,感谢@arne,我创build了这个类似的小函数来处理input被禁用和隐藏,或启用和显示的位置:

 function toggleInputState(el, on) { // 'on' = true(visible) or false(hidden) // If a field is to be shown, enable it; if hidden, disable it. // Disabling will prevent the field's value from being submitted $(el).prop('disabled', !on).toggle(on); } 

然后,一个jQuery对象(如$('input [name =“something”]'))只是简单地使用:

 toggleInputState(myElement, myBoolean)