jQuery在页面加载数据中设置选定的选项

时间:2012-03-08 20:13:59

标签: jquery json

我有一个页面使用jQuery加载页面加载时的选项下拉列表。那部分工作正常。然后我想在查询字符串的下拉列表中设置所选的选项(如果有的话) - 如果没有,则默认设置。查询字符串正在恢复正常,但我无法使所选选项的设置生效。在下面的代码中,当我停在“调试器”行并检查Select0时,它是未定义的(在成功加载之后)但是如果我允许代码继续运行,则下拉列表中填充了来自ajax调用的数据。我猜这就是为什么没有设置所选项目 - 只是无法弄清楚如何解决它。

    $(document).ready(function () {
    $.ajax({
           type: "POST",
           url: "myPage.aspx/MyWebMethod",
           contentType: "application/json; charset=utf-8",
           data: "{}",
           dataType: "json",
           success: function (states) {
               var jsonCodes = JSON.parse(states.d);
               for (var i in jsonCodes) {
                   $("#Select0").append(new Option(jsonCodes[i].regionname, jsonCodes[i].region_id));
               }
               var first = getUrlVars()["region"];
               if (first) {
                   $.fn.GetInventory(1, 10, reg, 'rank', 'asc'); // If there is a querystring use it
                   $("#Select0 option[text='" + reg + "']").get(0).selected = true;
               }
               else {
                    debugger;
                   var myText = 'United States';
                   $("#Select0 option[text='" + myText + "']").get(0).selected = true;
                   $.fn.GetInventory(1, 10, 'United States', 'rank', 'asc'); // If no query string default to USA          
               }
           }
       });

2 个答案:

答案 0 :(得分:4)

您正在尝试匹配不存在的text属性。你不能写:

$("#Select0 option[text='" + myText + "']").get(0).selected = true;

您可以改为使用filter()

$("#Select0 option").filter(function() {
    return $(this).text() == myText;
}).get(0).selected = true;

或者,更多地利用图书馆:

$("#Select0 option").filter(function() {
    return $(this).text() == myText;
}).first().prop("selected", true);

答案 1 :(得分:0)

您的代码中有两个错误。

$("Select0 option[text='" + reg + "']").get(0).selected = true;

这是不正确的。更改为 - >

$("#Select0 option[text='" + reg + "']").get(0).selected = true; 

另外:

$("Select0 option[text='" + myText + "']").get(0).selected = true;

这也是不正确的。改为:

$("#Select0 option[text='" + myText + "']").get(0).selected = true;

应该工作。