如何解决这个CSS不是函数错误

时间:2019-05-27 06:29:02

标签: javascript jquery html css

我有一个小的jQuery代码,但它给了我一些错误。有人可以帮我解决这个错误吗?

代码:

<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">
<input type="checkbox" checked>
<input type="checkbox">

JS

$(function() {
  var checkboxes = $("input[type=checkbox]")
      checkboxes.is(':checked').css('background-color', 'red')
      checkboxes.on('change', function() {
    var checkbox = $(this)
    checkbox.css('background-color', checkbox.is(':checked') ? 'blue' : 'transparent')
  })
})

CSS

  input[type='checkbox'] {
   -webkit-appearance: none; 
    width: 20px;
    height: 20px;
   background: grey;
 }

input[type='checkbox']:checked {
  background: red;}

这也是链接:     https://jsfiddle.net/3y9Lvobc/2/

控制台中的错误是:

 checkboxes.is(...).css is not a function

4 个答案:

答案 0 :(得分:4)

.is返回一个布尔值,而不是一个jquery对象。因此它没有.css方法。

您可以改用.filter

checkboxes.filter(':checked').css('background-color', 'red')

.filter将返回所有:checked复选框。

或者,您也可以使用if条件,如下所示:

if(checkboxes.is(':checked')) {
   checkboxes.css('background-color', 'red');
}

答案 1 :(得分:0)

因为is返回一个布尔值。使用find

checkboxes.find(':checked').css('background-color', 'red')

答案 2 :(得分:0)

那是因为它返回true / false

选中here

  

如果给定参数中至少有一个匹配项,则返回true,否则返回false。

答案 3 :(得分:0)

与其使用is(:checked)属性,而不是将其替换为find(:checked)来解决错误。检查下面的jQuery脚本

$(function() 
{
      var checkboxes = $("input[type=checkbox]")
          checkboxes.find(':checked').css('background-color', 'red')
          checkboxes.on('change', function() {
        var checkbox = $(this)
        checkbox.css('background-color', checkbox.is(':checked') ? 'blue' : 'transparent')
      })
    })

检查是否有帮助。

https://jsfiddle.net/gk6x8m5r/