我正在做一个项目,我必须在其中切换 <div>
的可见性.
我有以下代码:
<input type="radio" name="type" value="1"> Personal
<input type="radio" name="type" value="2"> Business
<div class="business-fields">
<input type="text" name="company-name">
<input type="text" name="vat-number">
</div>
我想切换业务领域 div。因此,如果没有任何单选按钮或“个人”单选按钮被选中: div 应该被隐藏。如果选择了“业务”单选按钮,我希望它显示。
目前,我正在使用这段代码:
$("input[name='type']").click(function() {
var status = $(this).val();
if (status == 2) {
$(".business-fields").show();
} else {
$(".business-fields").hide();
}
});
但是,我想知道我是否可以使用 .toggle() 函数来做到这一点。
最佳答案
我通常尽可能不使用 JS,因此这里出现了 HTML+CSS 方式的方法。
.bussines-type .business-fields {
display: none;
}
.bussines-type input[value="2"]:checked ~ .business-fields {
display: block;
}
<div class="bussines-type">
<input id="bt1" type="radio" name="type" value="1">
<label for="bt1"> Personal</label>
<input id="bt2" type="radio" name="type" value="2">
<label for="bt2"> Business</label>
<div class="business-fields">
<input type="text" placeholder="Company name" name="company-name">
<input type="text" placeholder="Vat number" name="vat-number">
</div>
</div>
~
代表我们在 ~
符号之前定义的元素之后的任何兄弟。
关于javascript - 如何使用单选按钮切换 div 可见性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27546071/