javascript javascript在复选框上隐藏/显示div:选中/未选中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19734907/
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
javascript Hide/show div on checkbox: checked/unchecked
提问by user2886091
I am trying to make a function in javascript, that will hide / show particular div in my registration form, depending on the state of my checkbox (checked or not). Here is my function:
我正在尝试在 javascript 中创建一个函数,它将在我的注册表单中隐藏/显示特定的 div,具体取决于我的复选框的状态(选中与否)。这是我的功能:
function doruc() {
var elem = document.getElementById('powermail_fieldwrap_331');
if (document.getElementById ('powermail_field_doruovaciaadresa2_1').checked) {
elem.display='block';
} else {elem.display:none;}
}
It isnt working. I am checking and unchecking my checkbox, but nothing happens. Oh and one more thing. I want that div to be initialized as hidden. Should I put in my css this? :
它不工作。我正在检查和取消选中我的复选框,但没有任何反应。还有件事儿。我希望该 div 被初始化为隐藏。我应该把这个放在我的css中吗?:
#powermail_fieldwrap_331{
display:none;
}
I would highly appreciate any suggestions.
我将不胜感激任何建议。
回答by Oriol
You could use
你可以用
var elem = document.getElementById('powermail_fieldwrap_331');
document.getElementById('powermail_field_doruovaciaadresa2_1').onchange = function() {
elem.style.display = this.checked ? 'block' : 'none';
};
If you want to hide it by default, you could use #powermail_fieldwrap_331{display:none;}
. But if you want to be sure, better use
如果你想默认隐藏它,你可以使用#powermail_fieldwrap_331{display:none;}
. 但如果你想确定,最好使用
var elem = document.getElementById('powermail_fieldwrap_331'),
checkBox = document.getElementById('powermail_field_doruovaciaadresa2_1');
checkBox.checked = false;
checkBox.onchange = function doruc() {
elem.style.display = this.checked ? 'block' : 'none';
};
checkBox.onchange();
回答by karaxuna
Try this:
试试这个:
elem.style.display='block'
回答by lior y
You should write it like this :
你应该这样写:
function doruc() {
var elem = document.getElementById('powermail_fieldwrap_331');
if (document.getElementById ('powermail_field_doruovaciaadresa2_1').checked) {
elem.style.display='block';
} else {elem.style.display='none';}}
and regarding your second question, you can either write in the div tag style="display:none"
or you can do as you said (add a class for the element).
关于你的第二个问题,你可以写在 div 标签中style="display:none"
,也可以按照你说的做(为元素添加一个类)。
回答by Rob Gibbons
You are correct in using display: none; to hide your DIV initially.
您使用 display: none 是正确的;最初隐藏您的 DIV。
As for your checkbox, try removing the spaces between getELementById and ('powermail_field...
至于您的复选框,请尝试删除 getELEmentById 和 ('powermail_field...
Also you need to change:
您还需要更改:
} else {elem.display:none;}
to:
到:
} else {elem.display = 'none';}