我的工作需要在页面上添加数百个 select
元素。我想在前一个更改时动态显示每个 select
。我有一个工作版本,其中我将所有 select
元素放入标记中,然后使用一个简单的函数将它们全部隐藏并仅显示第一个。然后在更改每个选择
时添加下一个。
这工作得很好,但显然并不理想。我不想在标记中放入 500 个 select
项并无缘无故地隐藏它们,而且我的 JS 函数将有 1500 行长。另外,这会让我觉得很愚蠢。
如何使用 JS 自动化此过程?
我不需要每个select
都有一个唯一的id
,但我确实需要每个select
有一个唯一且递增的 >名称
。这可能吗?我有一个工作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...
});
最佳答案
HTML:
<select class="hidden" id="one" name='name_0'>
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
jQuery
$('select').on('change', function() {
$('body').append($(this).clone(true))
})
结果:
请注意,我们正在使用clone() 方法的重载。这意味着事件处理程序和数据将与元素一起复制。因此,您附加到原始选择的任何事件处理程序都会被克隆。
如果您想增加名称,只需使用计数器并在克隆后添加属性:
cnt=0;
$('select').on('change', function() {
cnt++
$('body').append($(this).clone(true).attr('name', 'name_' + cnt))
})
关于javascript - 在更改前一个选择时添加具有唯一名称的新选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50537599/