2016-08-25 77 views
0

我在代碼上遇到語法問題(或者可能與選擇器有關)。請參閱demoJavaScript - 如果複選框已禁用,請使用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

您使用$(this)沒有宣佈任何事情。這就是它不起作用的原因。它在第二個例子中起作用,因爲.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

您可以使用:禁用選擇

see here