下拉列表 onchange 的问题

Issues with dropdown list onchange

可在此处找到 运行 代码:http://jsfiddle.net/rwdengmz/
我很抱歉,因为我无法清楚地解释我的问题,但这里是。 例如:当我点击 parent 1 时,它正确地显示了它存在于 child 中的值,即

这工作正常但是,问题出在我将 parent 选项更改为示例时,Parent 2. 然后它会再次显示正确的 child 值

但是,在打开下拉菜单之前,它将显示先前的 child 值,对于此实例,它将显示 parent 1 中的 child 1。

我如何才能只显示所选 parent 选项的特定 child 值?

<select id="parent">

    <option value="1">Parent 1</option>
    <option value="2">Parent 2</option>
    <option value="3">Parent 3</option>
</select>

<select id="child">
    <option data-parentid="1">Child 1 from Parent 1</option>
    <option data-parentid="1">Child 2 from Parent 1</option>
    <option data-parentid="2">Child 1 from Parent 2</option>
    <option data-parentid="2">Child 2 from Parent 2</option>
    <option data-parentid="3">Child 1 from Parent 3</option>
    <option data-parentid="3">Child 2 from Parent 3</option>
</select>

$("#parent").on("change", function()
{
    var id = $(this).val();

    $("#child option").each(function()
    {
        $(this).css("display", ($(this).data("parentid") == id ? "" : "none"));
    });
}).trigger("change");

您需要做的就是将 attr 设置为 selected。这应该可以帮助您解决尽管调用了 change 函数并根据需要填充了选项,但仍然显示先前值的问题。

$("#parent").on("change", function(){
    $('#child option').filter(function(){
        if($(this).data('parentid') == $('#parent').val()) {
            $(this).show().attr('selected','true');
        }
        else {
            $(this).hide();
        }
    });

});

查看 FIDDLE

试试这个代码

$("#parent").on("change", function()
{
    var id = $(this).val();
    $("#child").children('option').hide();
    $("select#child option[data-parentid="+id+"]").show().prop("selected", true);

}).trigger('change');