javascript - jquery设置选中的选择选项;不适用于动态添加的选项,但适用于静态选项

标签 javascript jquery asp.net-mvc-3

这是我正确填充选择列表的内容:

            <select id="countriesList">
                <option value="0"> -- select country -- </option>
                <option value="500"> 500 </option>
            </select>

            <script type="text/javascript">
                $(function () {
                    // load the countries list
                    $.getJSON(
                        "/StaticData/GetAllCountries/",
                        function (countries) {
                            // iterate each returned country and add it to the countries select list.
                            $.each(countries, function (i, country) {
                                $("#countriesList").append("<option value='" + country.Id + "'>" + country.Description + "</option>");
                            });
                        });

                    // set the selected country based on the model's delivered CountryId value
                    $('#countriesList').val(500);
                });
            </script>

人口工作得很好,但在脚本添加的选项元素之一上调用 .val() 不会使其被选中,但作为一个例子,当我调用 .val( 时,静态定义的选项“500”工作正常)就可以了。

我对 jquery 相当陌生,但不是编程,因为我正在进入浏览器编程。任何提示都会有用。您还需要什么?

此脚本代码直接位于表 td 标记内,因此在呈现表单时填充并设置选择。

最佳答案

尝试手动完成。

var select = document.getElementBydId("countriesList");
for (var i  = 0; i < select.options.length; i++) {
    if (select.options[i].value === "500") {
        select.selectedIndex = i;
    }
}

等等。问题是你使用的 AJAX 是异步的并且有回调

所以执行顺序是:

  • 获取JSON
  • 选择时设置值
  • 添加选项以供选择。

因此,将 $("#countriesList").val(500) 添加到回调函数的末尾

关于javascript - jquery设置选中的选择选项;不适用于动态添加的选项,但适用于静态选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4830040/

相关文章:

javascript - Flash 支持与安装的 Flash

asp.net-mvc-3 - 相对于 Asp.Net MVC 中的 View 路由图像?

javascript - 如果语句无法访问 body 元素,则设置路径点

javascript - JS 持续加载直到img src改变

javascript - Kendo Grid 自定义删除确认消息

javascript - jQuery Isotope 在 fitColumns 布局模式下不对齐大宽度元素

asp.net-mvc-3 - 工作单元和存储库模式是一起使用还是两个解决方案?

asp.net-mvc-3 - 编码为 utf 8 的 MVC 3 Razor 页面显示编码字符

javascript - 对象数组不工作

javascript - 为什么不在回调中使用函数?