jQuery create select list options from JSON, not happening as advertised?

对着背影说爱祢 提交于 2019-11-30 02:48:26

问题


How come this doesn't work (operating on an empty select list <select id="requestTypes"></select>

$(function() {

        $.getJSON("/RequestX/GetRequestTypes/", showRequestTypes);

    }
    );


    function showRequestTypes(data, textStatus) {

        $.each(data,
            function() {

                var option = new Option(this.RequestTypeName, this.RequestTypeID);
                // Use Jquery to get select list element
                var dropdownList = $("#requestTypes");

                if ($.browser.msie) {
                    dropdownList.add(option);
                }

                else {

                    dropdownList.add(option, null);

                }
            }
            );

        }

But this does:

  • Replace:

    var dropdownList = $("#requestTypes");

  • With plain old javascript:

    var dropdownList = document.getElementById("requestTypes");


回答1:


$("#requestTypes") returns a jQuery object that contains all the selected elements. You are attempting to call the add() method of an individual element, but instead you are calling the add() method of the jQuery object, which does something very different.

In order to access the DOM element itself, you need to treat the jQuery object as an array and get the first item out of it, by using $("#requestTypes")[0].




回答2:


By default, jQuery selectors return the jQuery object. Add this to get the DOM element returned:

 var dropdownList = $("#requestTypes")[0];



回答3:


For stuff like this, I use texotela's select box plugin with its simple ajaxAddOption function.



来源:https://stackoverflow.com/questions/94674/jquery-create-select-list-options-from-json-not-happening-as-advertised

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!