204

これが私のコードです:

$("#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で見つけられないようです。

4

6 に答える 6

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

メソッドは 2 つの.prop()引数を受け入れます。

  • プロパティ(disabled、checked、selected) true または false のいずれか
  • プロパティは、次のいずれかになります。
    • () - 現在の値を返します。
    • boolean (true/false) - プロパティ値を設定します。
    • function - 見つかった要素ごとに実行され、返された値を使用してプロパティが設定されます。2 つの引数が渡されます。最初の引数はインデックスです(0、1、2、検出された要素ごとに増加します)。2 番目の引数は、要素の現在の(true/false) です。

この場合、インデックス (i) と現在の値 (v) を提供する関数を使用してから、現在の値の逆を返したので、プロパティの状態が逆になります。

于 2012-02-28T20:43:15.127 に答える
103

完全なブラウザーの比較可能性を得るには、値を設定するか削除する必要があると思います! ここに私が作ったばかりの小さなプラグインがあります: disableddisabled

(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);
于 2011-01-15T20:55:04.707 に答える
21
    $('#checkbox').クリック(関数(){
        $('#submit').attr('disabled', !$(this).attr('checked'));
    });

于 2012-07-24T08:53:51.297 に答える
1

これは、次のコールバック構文を使用すると非常に簡単ですattr

$("#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
});
于 2011-01-15T20:43:18.207 に答える