我有一个小的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
答案 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)
答案 2 :(得分:0)
答案 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')
})
})
检查是否有帮助。