我有一个表单 UI,其中几个部分需要从单个可动态更新的选择列表中动态更新重复的 HTML 选择列表。
动态可更新列表工作得很好,因为可以动态添加和删除新选项。然后,我可以使用 JQuery .find() 让这个更新传播到每个重复的列表中。我什至添加了一些逻辑来维护原始选择列表的当前选定索引。
我无法做的是在原始选择列表中添加和删除新选项时保持每个重复选择列表的选定状态。由于对原始选择列表的每次更新都会遍历每个重复的选择列表,因此它们会丢失当前选择的选项索引。
这是我的难题的一个示例- *编辑-我鼓励您尝试并执行我在下面提供的代码并在提出解决方案之前应用您的理论,因为到目前为止没有任何建议有效。我相信你会发现这个问题比你一开始想象的要棘手得多:
<form>
<div id="duplicates">
<!--// I need for each of these duplicates to maintain their currently selected option index as the original updates dynamically //-->
<select>
</select>
<select>
</select>
<select>
</select>
</div>
<div>
<input type="button" value="add/copy" onclick="var original_select = document.getElementById('original'); var new_option = document.createElement('option'); new_option.text = 'Option #' + original_select.length; new_option.value = new_option.text; document.getElementById('original').add(new_option); original_select.options[original_select.options.length-1].selected = 'selected'; updateDuplicates();" />
<input type="button" value="remove" onclick="var original_select = document.getElementById('original'); var current_selected = original_select.selectedIndex; original_select.remove(original_select[current_selected]); if(original_select.options.length){original_select.options[current_selected < original_select.options.length?current_selected:current_selected - 1].selected = 'selected';} updateDuplicates();" />
<select id="original">
</select>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function updateDuplicates(){
$("#duplicates").find("select").html($("#original").html());
}
</script>
</form>
重要的是要注意,如果可能的话,重复的 HTML 选择列表应该保持一定程度的随意性(即没有 ID),因为这种方法需要通用地应用于整个文档中的其他动态创建的选择列表。
提前致谢!