JavaScript 如果 select 选项从其他方法更改,则不会触发 onchange 事件

JavaScript onchange event won't fire if select option is changed from other methods

我有一个 select 元素和一个 button

当 select 元素的选项发生变化时,它会调用一些函数:

<select id="mySel" onchange="someFunction();">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    ...
</select>

<input type="button" value="Click" onclick="document.getElementById('mySel').selectedIndex = 0;"/>

someFunction() 仅在我从 select 元素本身更改选项时被调用,而不是在我单击按钮时调用。

我想要做的是让 select 元素 onchange 事件触发,而不管选项是从哪里更改的。

我知道我可以将 someFunction() 添加到按钮的点击事件中,但这不是我想要的。

任何想法将不胜感激。

更改按钮 html。

<input type="button" value="Click" onclick="document.getElementById('mySel').selectedIndex = 0;someFunction();"/>

或者按照评论中提到的链接手动触发更改事件。

用这个你会得到你想要的。

function someFunction(select){
  console.log('reached here');
  
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="mySel" onchange="someFunction();">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    ...
</select>

<input type="button" value="Click" onclick="document.getElementById('mySel').selectedIndex = 0;someFunction();"/>

您可以在 DOM 加载时添加一个事件侦听器,这样您将在每次触发事件时获得事件回调 "programatically" 而在各自的元素标签中没有 "event calls" ,为您带来更简洁的代码。

运行这个例子,希望对你有帮助:

// Wait for WINDOW LOAD
window.onload = function() {
  // - Bind onchange event listener to the <select> DOMNode
  // - Your "someFunction" function is fired here!
  document.getElementById('mySel').addEventListener('change', someFunction); 
  
  // Trigger the change from the '#your_button' click callback
  document.getElementById('your_button').addEventListener("click", function () {
    // Create a new 'change' event
    var event = new Event('change');
    // Dispatch it
    document.getElementById('mySel').dispatchEvent(event);
  });
}

// Your function - Look at the console
function someFunction() {
  console.log('here!'); 
}
<select id="mySel">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>

<input type="button" id="your_button" value="Click" onclick="document.getElementById('mySel').selectedIndex = 0;"/>

您可以在以下位置查看更多信息:Select Tag Change Event Call on Selected Index Change