jquery-ui selectmenu - 在动态加载下拉选项时遇到 "no such method 'instance' for menu widget instance"

jquery-ui selectmenu - Encountered "no such method 'instance' for menu widget instance" while loading dropdown options dynamically

我有一个 ID 为 TestList 的下拉列表(select 列表)。

我想将其用作 jQuery UI 中的 selectmenu。此下拉列表正在动态填充,因此最初此 select 列表没有选项。 在脚本部分,我首先使用 select 菜单初始化 select 列表:

$("#TestList").selectmenu();

接下来,我想用数据动态填充它,所以我这样做了:

for (var i = 0; i < data.length; i++) {           
   $('#TestList').val(data[i]);
    $("#TestList").selectmenu("refresh");
} 

但问题是,它抛出 未捕获错误:菜单小部件实例没有这样的方法 'instance'。

我关注了How to select an option in a jQuery ui selectmenu dynamically?,但问题依然存在。 我正在使用最新的 jQuery UI 包(jquery-ui-1.12.1.custom)和 jQuery 1.9 请帮我解决这个问题.. 名单:

我创建了一个DEMO

这个演示:

  1. Dynamically initializes the selectmenu widget on the HTML dropdown
  2. Dynamically create/load options
  3. Dynamically select a specific option in the dropdown

我想这对你会有很大的帮助!

下面是DEMO中的完整代码:

<script>
  $( function() {
    $('#initialize').click(function() {
        $( "#speed" ).selectmenu();
      $('#status').html('The widget is now initialized. But it is still empty and does not contain any options.');
      $('#add_options').removeAttr('disabled');
      $('#initialize').attr('disabled','');
    });


        $('#add_options').click(function() {
        // Add a new option to the dropdown
        $('#speed').append($('<option>', {
          value: 1,
          text: 'Option 1'
      }));
      $('#speed').append($('<option>', {
          value: 2,
          text: 'Option 2'
      }));
      $('#speed').append($('<option>', {
          value: 3,
          text: 'Option 3'
      }));
      //Refresh the selectmenu widget so the newly added options to the dropdown are now loaded properly
      $( '#speed' ).selectmenu( "refresh" );

      $('#status').html('The new options are now added dynamically!!');
      $('#select_option').removeAttr('disabled');
      $('#add_options').attr('disabled','');
    });

    $('#select_option').click(function() {
        $( '#speed' ).val(3);
      $( '#speed' ).selectmenu( "refresh" );

      $('#status').html('Options 3 is now selected!!');
      $('#select_option').attr('disabled','');
    }); 
  });
  </script>

 <div class="demo">
 <input type="button" value="Initialize the Widget" id="initialize"/>
 <br><br>
 <input type="button" value="Dynamically Add New Options" id="add_options" disabled/>
 <br><br>
 <input type="button" value="Select the 'Option 3'" id="select_option" disabled/>
<form action="#">
  <br>
  <div id="status" style="font-weight:bold;">This is the simple default HTML dropdown</div>
  <br>
    <label for="speed">Select a speed</label>
    <select name="speed" id="speed">
    </select>

</form>

</div>