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

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

其他回答

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

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

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

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

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

我知道有几个迭代的答案,但现在这不需要jquery或任何其他外部库,可以很容易地完成只需以下。

文档。querySelector("#gate选项[value='Gateway 2']").setAttribute('selected',true); <选择id = "门" > <option value='null'>- choose -</option> . <option value='Gateway 1'>Gateway 1</option> . /option> . /option> <option value='Gateway 2'>Gateway 2</option> < /选择>

除了@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);