2016-03-11 100 views
0

我試圖模擬與選項元素'.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'

回答

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

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

如果我理解正確,myFunction()將b在最後的兩個其他操作之後,我們會調用它。

+0

是的,你已經理解了,但是,就像'.change'無法觸發,因爲所有的日誌都是相同的。但是如果我爲每個子節點在循環內手動執行命令,它將right和'.change'調用集中到'onchange函數',然後'myFunction'工作。 –