如何修改此 jQuery 以在下拉列表中动态显示和隐藏相关选择选项?

在此示例中,我有一系列 3 个选择下拉菜单。相同的类(“group-1”)应用于每个以指示它们是相关的(并允许在同一页面上选择多个组)。“data-parent”属性应用于 select 以建立 1:1 的父/子关系。“data-parent”属性应用于建立多对多关系的选项。

我的目标是创建一段动态 jQuery 代码,这样我就不必通过 id 或类显式标识行为,而是通过选项值和数据父值。

我的问题:

  1. 第三个下拉列表根本不更新。我认为它们中的一些可能具有多个数据父值(由空格分隔),但即使我将它们更改为全部只有一个,它仍然不会随着对第二个下拉列表的更改而更新.

  2. 我不确定如何在第三个下拉列表的选项中实现“许多”数据父值。拆分字符串,创建数组,查看数组中是否有值?

  3. 如何通过更改父下拉菜单将第二个和第三个下拉菜单重置为“默认”值?例如,如果我从第一个中选择“Cookies”,则第二个中会出现“1 dozen”和“2 dozen”。但是,如果我选择“一打”,然后将第一个框更改为“蛋糕”,则“一打”仍然处于选中状态,即使“片材”和“圆形”是下拉列表中唯一可用的选项。我想让它重置为默认值(“Desserts...”)。

代码在下面,这是我的工作 jsfiddle:https ://jsfiddle.net/rwh4z623/20/


交互式爱情
浏览 150回答 2
2回答

慕无忌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;}我不确定我是否过度评论了,如果有任何不清楚的地方,请随时发表评论。

偶然的你

您可以使用attributeContainsWord (~)将多个值与一个词匹配。因此,在下面的代码中,我使用$(this).children("option[data-parent~='" + selVal + "']").show();显示与匹配的选项selVal。另外,我使用&nbsp;prop('selectedIndex', 0);将选择重置为默认值。演示代码:$(document).ready(function() {&nbsp; $(".hide").children("option").hide();&nbsp; $("select").on('change', function() {&nbsp; &nbsp; //checking if dropdown is categories&nbsp; &nbsp; if ($(this).attr("name") == "categories") {&nbsp; &nbsp; &nbsp; //reset other to default&nbsp; &nbsp; &nbsp; $('select[name=desserts]').prop('selectedIndex', 0);&nbsp; &nbsp; &nbsp; $('select[name=flavors]').prop('selectedIndex', 0);&nbsp; &nbsp; }&nbsp; &nbsp; var selClass = $(this).attr("class");&nbsp; &nbsp; var selName = $(this).attr("name");&nbsp; &nbsp; var selVal = $(this).children("option:selected").val();&nbsp; &nbsp; //check if name != desserts&nbsp; &nbsp; if ($(this).attr("name") != "desserts") {&nbsp; &nbsp; &nbsp; //hide option of flavour&nbsp; &nbsp; &nbsp; $("select[name=flavors]").children("option").hide();&nbsp; &nbsp; &nbsp; //loop and show desire values&nbsp; &nbsp; &nbsp; $("select." + selClass + "[data-parent='" + selName + "']").each(function() {&nbsp; &nbsp; &nbsp; &nbsp; $(this).children("option[data-parent='" + selVal + "']").show();&nbsp; &nbsp; &nbsp; &nbsp; $(this).children("option[data-parent!='" + selVal + "']").hide();&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; //hide options&nbsp; &nbsp; &nbsp; $("select[name=flavors]").children("option").hide();&nbsp; &nbsp; &nbsp; //loop through flavours&nbsp; &nbsp; &nbsp; $("select[name=flavors]").each(function() {&nbsp; &nbsp; &nbsp; &nbsp; //use " ~ " to see if the selval matches with values&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $(this).children("option[data-parent~='" + selVal + "']").show();&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; });});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><select class="group-1" name="categories">&nbsp; <option value="" selected="selected">Please select...</option>&nbsp; <option value="cookie">Cookies</option>&nbsp; <option value="cake">Cakes</option>&nbsp; <option value="icecream">Ice Cream</option></select><select class="group-1 hide" name="desserts" data-parent="categories">&nbsp; <option value="" selected="selected">Desserts...</option>&nbsp; <option value="1-dozen" data-parent="cookie">1 dozen</option>&nbsp; <option value="2-dozen" data-parent="cookie">2 dozen</option>&nbsp; <option value="sheet" data-parent="cake">Sheet</option>&nbsp; <option value="round" data-parent="cake">Round</option>&nbsp; <option value="pint" data-parent="icecream">Pint</option></select><select class="group-1 hide" name="flavors" data-parent="desserts">&nbsp; <option value="" selected="selected">Flavors...</option>&nbsp; <option value="choc-chip" data-parent="1-dozen 2-dozen">Chocolate Chip</option>&nbsp; <option value="oatmeal" data-parent="1-dozen 2-dozen">Oatmeal</option>&nbsp; <option value="yellow" data-parent="sheet round">Yellow</option>&nbsp; <option value="red-velvet" data-parent="sheet">Red Velvet</option></select>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript