簡體   English   中英

JavaScript-如果禁用了復選框,則使用jQuery添加類

[英]JavaScript - If checkbox is disabled, add class using jQuery

我的代碼語法(或選擇器)有問題。 參見演示

我嘗試了以下代碼,但結果什么也沒做。

#1 hasAttribute():

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

#2。 is():

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");

任何想法?

謝謝。

您可以使用:disabled選擇器

看這里

您正在使用$(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");
    }
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM