我在一个项目中遇到了这个问题,所以我在小提琴上尝试了这个。我正在尝试动态触发选择菜单的选择。为什么我在选择菜单初始化中定义的
select
事件仅在我进行手动选择后才会触发?
我知道通过运行
$("#myselect").on("selectmenuselect")
这是可能的,但为什么它不起作用按照 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>
这样的事情应该可以解决问题:
$(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>