当页面加载后,从下拉列表中设置一个元素

Set an element from droplist when the page has been loaded

本文关键字:设置 元素 一个 下拉列表 加载      更新时间:2023-09-26

我尝试在加载页面时从下拉列表设置一个元素。我的代码:

<script>
$(document).ready(function() {
    console.log("ready!");
    changeStatus();
});
function changeStatus() {
    console.log("chStatus!");
    $('#status_change option:last').attr('selected', 'selected');
}
</script>
<select id="status_change">
    <option value="noselected">...</option>
    <option value="new">Processing</option>
    <option value="todrop">To drop</option>
    <option value="onbuyer">On buyer</option>
    <option value="resent">Resent</option>
</select>

最后一个选项不选择,当页面已加载?我的错误在哪里?

如果可能的话,您应该将该属性添加到元素本身,而不是在页面加载时添加。

<option value="resent" selected="selected">Resent</option>

$('#status_change option:last').attr('selected', 'selected');应该工作。然而,由于@Quentin Roy指出的浏览器不一致,它不能在Safari 9上工作。

作为一个选项,你也可以尝试prop

$('#status_change option:last').prop('selected', true);

可以设置select最后一个option的值。

$('#status_change').val($('#status_change option:last').val());