jQuery 如何使用复选框来切换另一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3642993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use a checkbox to toggle another element?
提问by Karem
How can I check if my checkbox with an id
of UseUsername
has been checked, and then use that information to toggle another element with an id
of div
?
如何检查带有id
of 的复选框是否UseUsername
已被选中,然后使用该信息切换带有id
of 的另一个元素div
?
回答by Harmen
It's as easy as:
这很简单:
$('#UseUsername').change(function(){
if($(this).is(':checked')){
$('#div').show();
} else {
$('#div').hide();
}
});
Additionally, you could fire this event when the page loads, so the div will disappear if the checkbox isn't checked.
此外,您可以在页面加载时触发此事件,因此如果未选中复选框,div 将消失。
// Show the div only if the checkbox is checked
function toggleDiv(){
if($(this).is(':checked')){
$('#div').show();
} else {
$('#div').hide();
}
}
$(document).onload(function(){
// Set change event to hide/show the div
$('#UseUsername')
.change(toggleDiv)
.trigger('change');
});
回答by user113716
A very simple way would be like this:
一个非常简单的方法是这样的:
$('#UseUsername').change(function(){
$('#div').toggle(this.checked); // show if it is checked, otherwise hide
});
Try it:http://jsfiddle.net/mHNuN/
试试看:http : //jsfiddle.net/mHNuN/