2016-08-25 3 views
0

私のコードで構文に問題があります。 demoを参照してください。JavaScript - チェックボックスが無効になっている場合、jQueryを使用してクラスを追加してください。

私は次のコードを試しましたが、結果は何もしません。

#1。 hasAttribute():

if ($('input[type=checkbox]').hasAttribute("disabled")) { 
    $(this).closest('.chkbox').addClass("is-disabled"); 
} 

#2。 ()である:

if ($('input[type=checkbox]').is("[disabled]")) { 
    $(this).closest('.chkbox').addClass("is-disabled"); 
} 
// ------------------------------------------------ 
if ($('input[type=checkbox]').is(":disabled")) { 
    $(this).closest('.chkbox').addClass("is-disabled"); 
} 

#3。小道具():

if ($('input[type=checkbox]').prop("disabled", true)) { 
    $(this).closest('.chkbox').addClass("is-disabled"); 
} 

それでは私はこの問題は、ライン上にあると思う:

$(this).closest('.chkbox').addClass("is-disabled"); 

任意のアイデア?

ありがとうございました。

を使用でき
+1

予想される結果は何ですか。デモはあなたが提供したコードと少し違っているようです – VladNeacsu

答えて

0

。それがうまくいかない理由です。 2番目の例では、.change()関数が変化している 'もの'(this)のコンテキストを与えるために動作します。

このコードは、必要に応じて機能するはずです。

$(function() { 

    // Grab all inputs with the type checkbox. 
    var input = $('input[type=checkbox]') 

    // Check for each of the input fields (i, el stands for index, element) 
    input.each(function(i, el) { 
    // Does it have the attribute disabled? 
    if(el.hasAttribute('disabled')) { 
     // Add the class 'is-disabled' 
     $(el).closest('.chkbox').addClass('is-disabled') 
    } 
    }) 

    $('input[type=checkbox]').change(function(){ 
    if ($(this).is(":checked")) { 
     $(this).closest('.chkbox').addClass("is-checked"); 
    } else { 
     $(this).closest('.chkbox').removeClass("is-checked"); 
    } 
    }); 
}); 
+0

if文でコマンドを実行するにはどうすればいいですか?それとも別の方法がありますか? –

+0

これはなぜ動作しないのか分かります。クラスを '.chkbox'に追加していますが、あなたのコードはクラスをフィールド自体に追加しています。私は正しい? –

+0

ああ、ええ、それの中に '.closest()'を入れるのを忘れました! – Roberrrt

1

:あなたは何かを宣言せず$(this)を使用している無効セレクタ

see here

関連する問題