반복구문에 관한 질문입니다. 아래의 자바 스크립트를 for문으로 만들려고 하는데 오동작을 합니다.
<원래 코드>
var $selectA1 = $( ‘#income_deduc1’ ),
$selectB1 = $( ‘#class_deduc1’ ),
$options1 = $selectB1.find( ‘option’ );
$selectA1.on( ‘change’, function() {
$selectB1.html( $options1.filter( ‘[class="’ + this.value + ‘"]’ ) );
} ).trigger( ‘change’ );
var $selectA2 = $( ‘#income_deduc2’ ),
$selectB2 = $( ‘#class_deduc2’ ),
$options2 = $selectB2.find( ‘option’ );
$selectA2.on( ‘change’, function() {
$selectB2.html( $options2.filter( ‘[class="’ + this.value + ‘"]’ ) );
} ).trigger( ‘change’ );
var $selectA3 = $( ‘#income_deduc3’ ),
$selectB3 = $( ‘#class_deduc3’ ),
$options3 = $selectB3.find( ‘option’ );
$selectA3.on( ‘change’, function() {
$selectB3.html( $options3.filter( ‘[class="’ + this.value + ‘"]’ ) );
} ).trigger( ‘change’ );
<바꾸려는 코드>
for(i = 1; i <= 3; i = i + 1){
var $selectA = $( ‘#income_deduc’ + i ),
$selectB = $( ‘#class_deduc’ + i ),
$options = $selectB1.find( ‘option’ );
$selectA.on( ‘change’, function() {
$selectB.html( $options.filter( ‘[class="’ + this.value + ‘"]’ ) );
} ).trigger( ‘change’ );
}