Javascript 给定复选框对象,输出其值
我有一个页面,其中有许多复选框。我想编写一个函数,当单击ckeckbox时将调用该函数,该函数确定是否选中该复选框Javascript 给定复选框对象,输出其值,javascript,jquery,checkbox,jquery-events,Javascript,Jquery,Checkbox,Jquery Events,我有一个页面,其中有许多复选框。我想编写一个函数,当单击ckeckbox时将调用该函数,该函数确定是否选中该复选框 <input type="checkbox" onclick="toggleVis('id', this);"/> ID <input type="checkbox" onclick="toggleVis('edit', this);" checked="checked"/> Edit <input type="checkbox" onclick=
<input type="checkbox" onclick="toggleVis('id', this);"/> ID
<input type="checkbox" onclick="toggleVis('edit', this);" checked="checked"/> Edit
<input type="checkbox" onclick="toggleVis('last', this);"/> Last
我愿意使用jQuery。您已经接近了
if(checkbox.checked) {
console.log('checked');
//...
}
没有
checked()
方法,但有一个checked
属性。请注意,您的代码只能在单击时工作。也许onchange
会更好?查看checkboxobj.checked
属性(而不是像函数一样调用它)。在您的情况下,如果(checkbox.checked){…},您可以引用。更多信息请参见和基于JQuery的解决方案:
var checked = $(checkbox).is(':checked');
如果您想通过某个JQ选择器首先找到复选框,则此选项非常有用。ID
<input type="checkbox" class="checkthis"> ID
<input type="checkbox" class="checkthis" checked="checked"> Edit
<input type="checkbox" class="checkthis"> Last
$(input.checkthis).click(function() {
if($(this).is(':checked') {
// do checked stuuf
} else {
// do not checked stuff
}
});
编辑
最后
$(input.checkthis)。单击(函数(){
如果($(this).is(“:选中”){
//你喜欢斯图夫吗
}否则{
//不要检查东西
}
});
如果要使用jQuery执行此操作,可以尝试以下操作。请注意,我绑定到复选框,而不是直接在HTML元素上包含“onclick”或“onchange”
$('[type=checkbox]').click(function(){
if( $(this).attr('checked') ){
console.log('checked');
if($('.'+$(this).attr('name')).css('display') != "none") {
$('.'+$(this).attr('name')).css('display', 'none');
} else {
$('.'+$(this).attr('name')).css('display', 'table-cell');
}
}
});
你的代码工作了吗?如果没有,发生了什么?获取Firebug并查看实际传递的对象是什么。
$('[type=checkbox]').click(function(){
if( $(this).attr('checked') ){
console.log('checked');
if($('.'+$(this).attr('name')).css('display') != "none") {
$('.'+$(this).attr('name')).css('display', 'none');
} else {
$('.'+$(this).attr('name')).css('display', 'table-cell');
}
}
});