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

simulate click on option and wait for change event to finish

本文关键字:事件 等待 单击 选项 模拟      更新时间:2023-09-26

我正在尝试通过对选项元素使用".each"jquery函数循环来模拟点击。

但是,此选择具有关联的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() );
}

如果我理解正确,最后将在其他 2 个操作之后调用myFunction()