【发布时间】:2018-11-05 08:22:43
【问题描述】:
我的工作需要一个页面上有数百个 select 元素。我想动态显示每个select,因为前一个发生了变化。我有一个工作版本,其中我将所有select 元素放在标记中,然后使用一个简单的函数将它们全部隐藏并仅显示第一个。然后在更改每个 select 时添加下一个。
这很好用,但显然并不理想。我不想在标记中放置 500 个 select 项目并无缘无故地隐藏它们,我的 JS 函数将有 1500 行长。再加上那会让我觉得很傻。
如何使用 JS 自动化这个过程?
我不需要每个select 都有一个唯一的id,但我确实需要每个select 都有一个唯一且递增的name。这可能吗?我有一个工作的fiddle。
HTML:
<select name="select-one" class="hidden" id="one">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
<select name="select-two" class="hidden" id="two">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
<select name="select-three" class="hidden" id="three">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
<select name="select-four" class="hidden" id="four">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
JS:
$(document).ready(function() {
$('.hidden').hide();
$('#one').show();
$('#one').change(function(){
$('#two').show();
});
$('#two').change(function(){
$('#three').show();
});
$('#three').change(function(){
$('#four').show();
});
// and so forth...
});
【问题讨论】:
标签: javascript jquery html html-select onchange