JQuery刷新选择框

问题描述 投票:11回答:5

我使用此方法在页面加载时使用JQuery填充选择字段

 $('#select').append('<option value="' + result + '">' + result + '</option>'); 

但是这会使选择框“空白”,即选项列表中的第一个值不会被预先选为选定选项。

如何“刷新”此列表以便预先选择第一个值?

对不起 - 应该说以前是JQuery mobile

谢谢。

jquery select jquery-mobile option
5个回答
21
投票

您可以将“selected”属性添加到您要选择的选项元素中:

$('#select')
    .append('<option value="' + result + '" selected="selected">' + result + '</option>'); 

您没有指定如何使用循环精确填充选择元素,您可以这样做:

var data = ['a', 'b', 'c'];
var $select = $('#select'); // you might wanna empty it first with .empty()

for (var i = 0; i < data.length; i++) {
    var o = $('<option/>', { value: data[i] })
        .text(data[i])
        .prop('selected', i == 0);
    o.appendTo($select);
}​

DEMO


所以你似乎正在使用jQuery Mobile,就像你在评论中所说的那样。

如果您使用的是selectmenu小部件,则需要在对其内容/结构进行编程更改后以编程方式刷新:

$select.selectmenu("refresh", true);

Documentation


4
投票

你可以用

$('#select').removeAttr('selected').find('option:first').attr('selected', 'selected');

3
投票

简单..你设置任何你想要的值,即:$('#select').val(5); ..所以在你的情况下它的$('#select').val(result);

编辑:一个完整​​的工作示例包括:

<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.4.js'></script>
<select id='select'></select>
<br>
<input type=button onclick='addNew()' value='Add'>

<script>
function addNew()
{
        var result = Math.floor(Math.random()*1000);
        $('#select').append('<option value="' + result + '">' + result + '</option>'); 
        $('#select').val(result);           
} 
</script>


1
投票

添加新选项后,并非所有浏览器都会自动刷新选择。

对我有用的一个技巧是在向其添加新选项后隐藏并显示选择框。所以在你的情况下:

 $('#select').append('<option value="' + result + '">' + result + '</option>').hide().show();

至于选择正确的新添加选项,请遵循:

 $('select').val(result);

1
投票

Mohora Bogdan的答案只能使用一次,如果你选择另一个选项,它就不再起作用了。

为了使其可重复使用:

$('#select').prop('selected', false).find('option:first').prop('selected', true);
© www.soinside.com 2019 - 2024. All rights reserved.