下拉菜单未调用 onChange 函数

onChange function not getting invoked for dropdown menu

我有一个 按钮 ,单击它会将下拉菜单重置为其默认选项。

我有一个下拉菜单的 onchange 事件侦听器。 单击按钮时事件侦听器未被触发。

HTML 代码

<select id="my_select">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>
<div id="reset">reset</div>
$("#reset").on("click", function () {
document.getElementById('my_select').selectedIndex = 0;
});
$("#my_select").change(function(){
alert("Hi");
});

上面的更改代码在点击x时不会触发,而在手动更改时会触发。 我希望它适用于 document.getElementById('Typess').selectedIndex = 1;以及。 如何进行这项工作?

试试这个:

    $(".x").click(function(event){
    // alert(" x is clicked") (This alert is working)
     document.getElementById('Typess').val(1);
    })

还要确保您确实更改了值,而不是尝试设置相同的值

该事件 change 被触发是因为用户对该元素进行了更改。

另一种方法是手动触发该事件,如下所示:

let $typess = $("#Typess")
$(".x").click(function(event) {
  document.getElementById('Typess').selectedIndex = 1;
  $typess.trigger("change");
})

$typess.on('change', function(event) {
  console.log("Changed");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Typess">
<option>A</option>
<option>B</option>
</select>
<p>
<button class="x">Click me!</button>

尝试在 click 中实施您的 change 活动:

$("#reset").on("click", function () {
document.getElementById('my_select').selectedIndex = 0;

  $("#my_select").change(function(){
  alert("Hi");
  });
});

触发更改事件

$("#reset").on("click", function () {
document.getElementById('my_select').selectedIndex = 0;
$("#my_select").change()
});