如何在不重新填充列表的情况下维护下拉列表的当前信息

How can I maintain a a dropdown's current information without repopulating the list?

本文关键字:情况下 列表 维护 下拉列表 信息 填充 新填充      更新时间:2023-09-26

目前,我有一个下拉列表,其中填充了SQL数据库中的团队名称:

$(".show_hide2").click(function () {
    ("#team").find("tr:gt(0)").remove();
    $(".slidingDiv2").slideToggle();
    teams = $.parseJSON(getTeams());
    for (i = 0; i < teams.length; i++) {
        var team = getTeam(teams[i]);
        updateTeamBoard(team);
        populateTeamSelection(team);
    }
}

下面是用于填充下拉列表的代码。

.JS:

function populateTeamSelection(team) {
    var team = $.parseJSON(team);
    $("#teamSelection").find("#tr:gt(0)").remove();
    $("<option value='" + team.teamID + "'>" + team.teamName + "</option>").appendTo("#teamSelection");
}

.HTML:

<div class="slidingDiv2">
    <select id="teamSelection">
        <option id="default" value="0">Select A Team</option>
    </select>
    <input type="button" id="teamViewer" value="Team Viewer"></input>
</div>

问题是,每次我单击显示/隐藏按钮时,它都会保留列表中的当前信息,然后将相同的信息添加到列表中。我正在使用 AJAX 动态生成表和列表,但由于某种原因我无法弄清楚这一点,我有一种感觉它相当简单。任何帮助将不胜感激。

每次单击时,都会调用populateTeamSelection()。每次调用populateTeamSelection()时,它都会将某些内容附加到列表中。快速解决方法是在添加任何项目之前从列表中删除所有项目。

您可以使用$('select').children().remove()for循环之前删除所有option项目。

$(function ($)
{
    $populateTeamSelection = function(team)
    {
        $result = $.parseJSON(team,function(call){$handle = call;});
        $result.success(function(){ $data = $handle; });
        $result.error(function()
        {
            //Do something or nothing on error
        });
        $result.complete(function()
        {
            //Clear all current options first
            $('#teamSelection').html('');
            //Populate with new data
            $.each($data,function(lable,value)
            {
                $("#teamSelection").append($("<option></option>").attr("value",value['teamID']).text(value['teamName']));
            });
        });
    };
}(jQuery));
$(document).ready(function()
{
    $('.show_hide2').click(function()
    {
        $(".slidingDiv2").slideToggle();
        $populateTeamSelection(team);
    });
});
相关文章: