使用jQuery切换输入禁用属性

Tom*_*old 177 jquery toggle attr

这是我的代码:

$("#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.
});
Run Code Online (Sandbox Code Playgroud)

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

我似乎无法在Google上找到它.

Arn*_*rne 421

$('#el').prop('disabled', function(i, v) { return !v; });
Run Code Online (Sandbox Code Playgroud)

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

  • 属性名称(已禁用,已选中,已选中)是true或false的任何内容
  • 属性,可以是:
    • () - 返回当前值.
    • boolean(true/false) - 设置属性值.
    • function - 对每个找到的元素执行,返回的值用于设置属性.有两个论点通过; 第一个参数是索引(0,1,2,每个找到的元素增加).第二个参数是元素的当前(true/false).

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

  • 什么是"我"和"v"? (4认同)
  • 作为更新,使用箭头函数看起来非常整洁:`$('#el').prop('disabled',(i,v)=>!v);` (4认同)
  • Upvoted as(我相信).prop()是正确的方法,并且正是为了设置像disabled ="disabled"+它的优雅这样的东西而添加的 (2认同)

ifa*_*our 101

获得完整的浏览器的可比性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);
Run Code Online (Sandbox Code Playgroud)

示例链接.

编辑:更新示例链接/代码以保持可链接性!
编辑2:
基于@lonesomeday评论,这是一个增强版本:

(function($) {
    $.fn.toggleDisabled = function(){
        return this.each(function(){
            this.disabled = !this.disabled;
        });
    };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

  • 这可能有用,但它会很慢,因为你不断创建新的jQuery对象.`$ .fn.toggleDisabled = function(){return this.each(function(){this.disabled =!this.disabled;});}`就是你所需要的. (27认同)
  • 对于任何未来的googlers,此解决方案同样适用于"required"属性. (2认同)

小智 19


    $('#checkbox').click(function(){
        $('#submit').attr('disabled', !$(this).attr('checked'));
    });

  • 注意:仅适用于jQuery 1.6.在两个出现时使用.prop()而不是attr()来获取布尔值.见http://api.jquery.com/prop/ (2认同)

小智 7

另一个简单的选项,单击复选框即可更新。

HTML:

<input type="checkbox" id="checkbox/>
<input disabled type="submit" id="item"/>
Run Code Online (Sandbox Code Playgroud)

jQuery:

$('#checkbox').click(function() {
    if (this.checked) {
        $('#item').prop('disabled', false); // If checked enable item       
    } else {
        $('#item').prop('disabled', true); // If checked disable item                   
    }
});
Run Code Online (Sandbox Code Playgroud)

在行动:链接

  • 用 `$('#item').prop('disabled', this.checked);` 去掉 `if` 块 (10认同)