我想设置一个选项,之前选择显示在页面加载。我尝试了下面的代码:

$("#gate").val('Gateway 2');

with

<select id="gate">
    <option value='null'>- choose -</option>
    <option value='gateway_1'>Gateway 1</option>
    <option value='gateway_2'>Gateway 2</option>
</select>

但这并不奏效。什么好主意吗?


当前回答

这很好。看这个小提琴:http://jsfiddle.net/kveAL/

是否有可能需要在$(document).ready()处理程序中声明jQuery ?

另外,是否可能有两个具有相同ID的元素?

其他回答

$(document).ready(function() {
    $("#gate option[value='Gateway 2']").prop('selected', true);
    // you need to specify id of combo to set right combo, if more than one combo
});

有些情况可能是

$('#gate option[value='+data.Gateway2+']').attr('selected', true);
// Make option have a "selected" attribute using jQuery

var yourValue = "Gateway 2";

$("#gate").find('option').each(function( i, opt ) {
    if( opt.value === yourValue ) 
        $(opt).attr('selected', 'selected');
});
$(function() {
$("#demo").val('hello');
});

这肯定能起作用。这是一个演示。确保你已经把你的代码放在$(document).ready中:

$(function() {
    $("#gate").val('gateway_2');
});