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

$("#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>

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


当前回答

除了@icksde和@Korah(谢谢两位!)

当使用AJAX构建文档的选项时。Ready可能在构建列表之前被触发,因此这可能会提供一些见解。

超时确实有效,但正如@icksde所说,它很脆弱。最好把它放在AJAX函数中,像这样:

$("#someObject").change(function() {
    $.get("website/page.php", {parameters}, function(data) {
        $("#gate").append("<option value='Gateway 2'">" + "Gateway 2" + "</option>");
        $("#gate").val('Gateway 2');
    }, "json");
});

其他回答

我发现使用jQuery .val()方法有一个显著的缺点。

<select id="gate"></select>
$("#gate").val("Gateway 2");

如果该选择框(或任何其他输入对象)位于表单中,并且表单中使用了重置按钮,那么当单击重置按钮时,设置的值将被清除,而不是像您所期望的那样重置为初始值。

这似乎最适合我。

对于选择框

<select id="gate"></select>
$("#gate option[value='Gateway 2']").attr("selected", true);

对于文本输入

<input type="text" id="gate" />
$("#gate").attr("value", "your desired value")

对于textarea输入

<textarea id="gate"></textarea>
$("#gate").html("your desired value")

对于复选框

<input type="checkbox" id="gate" />
$("#gate option[value='Gateway 2']").attr("checked", true);

单选按钮

<input type="radio" id="gate" value="this"/> or <input type="radio" id="gate" value="that"/>
$("#gate[value='this']").attr("checked", true);

$(" #门”)。瓦尔(“网关2”)。道具(“选择”,真正的);

$(function() {
$("#demo").val('hello');
});

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

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

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

// 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');
});