选择刚刚附加 jquery 的选项

2022-01-22 00:00:00 append select jquery javascript option

基于 AJAX 查询,我将一些选项附加到列表中.

Based on an AJAX query I appended some options to a list.

for(var i = 0; i < options.length; i++) {
    var data = options[i];
    var option = $('<option id="mySelectElementOption_' + data['id'] + '" value="' + data['value'] + '">' + data['value'] + '</option>');
    $('#mySelectElement').append(option);
}

现在,当用户在页面上进行交互时,我想选择刚刚附加的选项,我尝试了以下方法(这两种可能性都不适合我):

Now when the user interacts on the page i want to select on of the just appended options and i tried the following (both possibilities don't work for me):

$('#mySelectElementOption_' + id).attr('selected', 'selected');

var option = document.getElementById('mySelectElementOption_' + id);
option.selected = true;

所以我被卡住了,因为我不知道如何选择我的选项.你有什么想法我可以解决这个问题吗?谢谢!

So I'm stuck, because I don't know how to select my option. Do you have any idea(s) how I can solve this? Thanks!

P.S.:当我在 Google Chrome 中尝试第二种可能性时,它运行良好.

你好,约瑟夫

推荐答案

var opts = {

success: function(data)
         {
             //do everything here first before appending it,
             //including adding event bindings
         }

}

$.ajax(opts)

相关文章