慕无忌1623718
我不知道这段代码的上下文,所以我不知道这种“嵌套”选项和选择模式是否是最佳解决方案。但这是我的 javascript 版本,它似乎实现了问题中的要求。我会评论相关的变化,这样我的思维过程就很清楚了。我还为隐藏类添加了 css,因为它不在 jsfiddle 中。$(document).ready(function () { $("select").on('change', function () { var selClass = $(this).attr("class"); var selName = $(this).attr("name"); var selVal = $(this).children("option:selected").val(); //Call the update function with the data of the changed Select updateRecursivly(selClass, selName, selVal); //Recursive function to update all selects, this allows for multiple "child" selects per select and an in theory infinite "tree" of selects function updateRecursivly(selClass, selName, selVal) { //Search "children" of the parent select var children = $("select." + selClass + "[data-parent='" + selName + "']"); if (children.length) { children.each(function () { //Hide all options in the "child" select $(this).children("option[data-parent]").hide(); //if selVal is an empty string, the default option is selected and we should just hide the "child" select if (selVal !== "") { //Get all options that contain (*=) selVal in "data-parent" var options = $(this).children("option[data-parent*='" + selVal + "']"); //If there are possible options show the select and the possible options. Else hide select if (options.length) { $(this).removeClass('hide'); options.show(); } else { $(this).addClass('hide'); } } else { $(this).addClass('hide'); } //If the select is updated, the options should be reset. Any selected is reset and the first is selected //From here https://stackoverflow.com/a/16598989/14040328 this is apparently safer against reset events than other solutions $(this).children("option:selected").prop("selected", false); $(this).children("option:first").prop("selected", "selected"); //Get the name of the select var childName = $(this).attr("name"); //Update the Child select updateRecursivly(selClass, childName, ""); }); } } });});.hide { display: none;}我不确定我是否过度评论了,如果有任何不清楚的地方,请随时发表评论。