我正在尝试制作一个在用户做出选择后发生变化的表单.
如果用户选择“选项A”,则显示具有“option1”类的div的内容.
如果用户选择“选项A”,则显示具有“option1”类的div的内容.
我已经用非常简单的jquery完成了这个(参见下面的代码或jsfiddle).
我无法弄清楚的是如何让它变得动态.
以下是我将如何做到这一点:
>从“#select”获取所有选项值并放入数组.
>用新数组替换“hideAll”函数的内容.
>制作一些通过数组运行的“for-each-function”
制作if stament.
注意:选项值始终与div类相同.
var hideAll = function() { $('.option1,.option2,.option3').hide(); } $('#select').on('change',function() { hideAll(); var category = $(this).val(); console.log(category); if (category === 'option1') { $('.option1').show(); } if (category === 'option2') { $('.option2').show(); } if (category === 'option3') { $('.option3').show(); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form method="post"> <label for="option">Options</label> <select name="select" id="select"> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3">Option 3</option> </select> <div class="option1" style="display:block;"> <label for="countries">Countries</label> <select name="countries"> <option value="denmark">Denmark</option> <option value="norway">Norway</option> <option value="uk">UK</option> </select> </div> <div class="option2" style="display:none;"> <label for="letters">Letters</label> <select name="letters"> <option value="a">A</option> <option value="b">B</option> <option value="c">C</option> </select> </div> <div class="option3" style="display:none;"> <label for="numbers">Numbers</label> <select name="numbers"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </div> </form>
解决方法
根本不需要循环,你可以只搜索任何以class开头的div:
var hideAll = function() { $('div[class^=option]').hide(); } $('#select').on('change',function() { hideAll(); var category = $(this).val(); $('.' + category).show(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form method="post"> <label for="option">Options</label> <select name="select" id="select"> <option value="option1">Option 1</option> <option value="option2">Option 2</option> <option value="option3">Option 3</option> </select> <div class="option1" style="display:block;"> <label for="countries">Countries</label> <select name="countries"> <option value="denmark">Denmark</option> <option value="norway">Norway</option> <option value="uk">UK</option> </select> </div> <div class="option2" style="display:none;"> <label for="letters">Letters</label> <select name="letters"> <option value="a">A</option> <option value="b">B</option> <option value="c">C</option> </select> </div> <div class="option3" style="display:none;"> <label for="numbers">Numbers</label> <select name="numbers"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </div>