jQuery UI selectmenu:为什么"选择"事件没有触发?

时间:2017-01-24 14:52:20

标签: javascript jquery jquery-ui

我在一个项目中遇到了这个问题所以我试着这个小提琴。我试图动态触发选择菜单。为什么我在selectmenu的初始化中定义的select事件仅在我进行手动选择后触发?

我知道这可以通过运行$("#myselect").on("selectmenuselect") 来实现,但为什么它不起作用as suggested by the API



$(function () {
   $("#myselect").selectmenu({
       select: function () {
           alert("ok");
       }
   });
   setTimeout(function () {
       $("#myselect").val("option4");
       $("#myselect").selectmenu("refresh");
       $("#myselect").trigger("selectmenuselect");
    }, 1000);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<select id="myselect">
  <option value="option1" selected>option 1</option>
  <option value="option2">option 2</option>
  <option value="option3">option 3</option>
  <option value="option4">option 4</option>
</select>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

这样的事情可以解决问题:

$(function () {      
  
    $("#myselect").selectmenu().on("selectmenuselect", function (event, ui) {
         console.log(ui);
    });
  
   setTimeout(function () {
       $("#myselect").val("option4");
       $("#myselect").selectmenu("refresh");
       $("#myselect").trigger("selectmenuselect",$("#myselect"));
    }, 1000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<select id="myselect">
  <option value="option1" selected>option 1</option>
  <option value="option2">option 2</option>
  <option value="option3">option 3</option>
  <option value="option4">option 4</option>
</select>

祝你有个美好的一天!