Blank Option Text using $(dropdown).append(new Opt

2019-07-12 16:27发布

问题:

The following code works correctly in both Chrome and Firefox. In IE 9 the options are appended, but the Text is always blank.

function populateDeveloperDropDownViaSkillProfileSpecificAjaxcall(dropdown, selectedProfileId, selectedDeveloperId) 
{
    $(dropdown).prepend("<option value=''></option>");
    $.getJSON(ajaxActionToGetFilteredDeveloperList, { skillProfileId: selectedProfileId, "selectedDeveloperId": selectedDeveloperId },
        function (data) {
            var opt;
            //Returns a List of ASP.NET MVC SelectListItem serialized to JSON
            $.each(data, function (k, v) {
                if (v != undefined && v.Selected == true) {
                    opt = new Option(v.Text, v.Value, true, true);
                }
                else {
                    opt = new Option(v.Text, v.Value);
                }
                $(dropdown).append(opt);
            });

        }
    );
}

Does anybody see something that I'm doing wrong or have a work-around for this? Apologies if this is a dumb error, but I've spent several hours on it and I'm just banging my head at this point.

回答1:

This could be related to a weird issue affecting past IE versions; to overcome it, I would try to force IE to update the option text after it has been appended:

if (v != undefined && v.Selected == true) {
    opt = new Option(v.Text, v.Value, true, true);
}
else {
    opt = new Option(v.Text, v.Value);
}

$(dropdown).append(opt);
$(opt).text(v.Text);

I don't know if this is the cause of your issue or not, but it is better to try.