2014-12-04 81 views
0

我正在使用jQuery。我的页面中有一个选择标签。页面加载时无法使用javascript设置选择选项

<select id="sel"> 
    <option value="1">One</option> 
    <option value="2">Two</option> 
</select> 

我从我的服务器一定的价值与阿贾克斯在加载页面。

$().ready(function() { 
    $.post(url, function(result) { 
    var value = result.value; // for example, result can be {value: "1"}. 
    console.log($("#sel")[0].options.length); // output: 0 // EMPTY options ?? 
    $("#sel").val(value); 
    }); 
}); 

但是我选择的选项没有改变。 select标签似乎没有选项。 不应该在这种情况下DOM已经完全加载?

我可以设置所选的选项,当页面加载和用户触发一些行动。

+0

凡'value'定义?我没有在你的代码中看到它。 – scunliffe 2014-12-04 01:39:54

+0

@scunliffe:没关系。关键是在这种情况下,select标签似乎根本不包含任何选项。 – 2014-12-04 01:48:37

+0

@Cattla:没关系。即使我直接将'value'设置为字符串,它也不起作用。 – 2014-12-04 01:53:38

回答

0

尝试这种变化,这应该工作,因为你可能已经想要它。

Im假设resultValue是select的选项索引。

$().ready(function() { 
    $.post(url, function(result) { 
    var resultValue = result.value; // for example, result can be {value: "1"}. 
    var select = $('#sel'); 
    var opts = $(select[0].options).toArray(); 
    console.log(opts); // output will be the number of child nodes within the Select 

    // Setting the new value of the select, based on the result.value 
    select.val(opts[resultValue].value); 
    }); 
}); 
0

试试这个

$.post(url, function(result) { 
    var value = result.value; 

    $("#sel option[value="+value+"]").attr("selected", true); 
    }); 
相关问题