模拟点击选项并等待更改事件完成

simulate click on option and wait for change event to finish

我正在尝试通过选项元素上的“.each”jquery 函数循环来模拟点击。

但是,这个 select 有一个关联的 onchange 函数,可以更改另一个输入的值。

到目前为止,这是我的代码:

$('#selectItem').on('change', function() {
  console.log( $('#inputToWatch').val() );
});
$('#selectItem').children().each(function( index ) {
    $( this ).attr('selected', 'selected').parent().focus();
    $( this ).parent().change();
});

/*I also tried this way
$('#selectItem').children().each(function( index ) {
    $( this ).attr('selected', 'selected').parent().focus();
    setTimeout(function(){ $( this ).parent().change(); }, 3000);
    console.log( index + ": " + $('#inputToWatch').val() );
});
*/

而且html看起来像

<select id="selectItem" onchange="changeFunc(this)">
   <option value="option1" selected="selected">option1</option>
   <option value="option2" selected="selected">option2</option>
   <option value="option3" selected="selected">option3</option>
   <option value="option4" selected="selected">option4</option>
</select>

我无法让 jquery 等到 'changeFunc' 结束才能记录 '#inputToWatch'

的值
$('#selectItem').children().each(function( index ) {
    $( this ).attr('selected', 'selected').parent().focus();
    $( this ).parent().change();
    myFunction();
});

function myFunction(){
  console.log( $('#inputToWatch').val() );
}

如果我没理解错的话,myFunction() 将在最后的 2 个其他操作之后调用。