首页 > 解决方案 > jquery隐藏选择以前的值和onchange显示新值下拉

问题描述

我在 jquery 上遇到了一个问题。我想隐藏选择值(以前的值),但是如果更改下拉列表,它会显示新值并从所有下拉列表中隐藏以前的值。

HTML 下拉菜单

<select class="gr-fields-select">
<option value="">Select</option>
<option value="18355">Product Management</option>
<option value="18356">QA</option>
<option value="18357">Sales</option>
<option value="98595">Support</option>
<option value="05223">Test group</option>
<option value="05224">Test group one user</option>
</select>
</div>

这是我的 jquery 函数

function hideSelectedValues(){
$("select").each(function(){
    let selectValue = $(this).val();
    if(selectValue == "Select" || selectValue == "") return;
    $(this).addClass("currentSelection");

    $("select").each(function(){
        if(!$(this).hasClass("currentSelection")){              
            let previousValue = $(this).val();                  
            $(this).find(`option[value='${previousValue}']`).hide();
        }
        else{
            $(this).on('change',function () {      //change and show newValue     
                let newValue = $(this).val();
                $(this).find(`option[value='${newValue}']`).show();
                $(this).find(`option[value='${previousValue}']`).hide();  //Error undefined
            });
        }

    });
    $(this).removeClass("currentSelection");
})
}

此功能不起作用。我无法从 IF 条件中获取先前的值并在 ELSE 正文中传递先前的值以隐藏先前的值,但它给出了错误先前的值未定义

我在这个功能中犯了什么错误?

谁能帮我?

标签: jqueryselectdrop-down-menudropdownshow-hide

解决方案


onchange="if($(this).val()=='1') $('#18355').show();else $('#18355').hide();

推荐阅读