2016-04-02 10 views
0

この関数をより一般的に書くにはどうすればよいですか?だから私はこれを何度も何度も繰り返す必要はないのですか?複数の入力で同様の変更イベントハンドラを簡略化

jQuery("input[name='option1']").change(function() { 
    $("#option1").addClass('highlight'); 
    setTimeout(function() { 
     $("#option1").removeClass("highlight"); 
    }, 100); 
}); 

jQuery("input[name='option2']").change(function() { 
    $("#option2").addClass('highlight'); 
    setTimeout(function() { 
     $("#option2").removeClass("highlight"); 
    }, 100); 
}); 

jQuery("input[name='optionX']").change(function() { 
    $("#optionX").addClass('highlight'); 
    setTimeout(function() { 
     $("#optionX").removeClass("highlight"); 
    }, 100); 
}); 
+0

あなたは私たちが要素をDOMで互いにどのように関係するかを見ることができる質問には、あなたのHTMLを追加してくださいすることができます。 –

答えて

2

あなたは名前がoptionで始まるすべての<input>要素にイベントをバインドするattribute starts with selectorを使用することができます。

// Bind change event on all the `<input>` elements whose `name` attribute starts with `option`. 
$('input[name^="option"]').change(function() { 
    // Get the `name` of this element 
    var name = $(this).attr('name'), 
     elem = $('#' + name); // Get the corresponding element whose id is same as the name of this element 

    elem.addClass('highlight'); 
    setTimeout(function() { 
     // Use cached element object 
     elem.removeClass('highlight'); 
    }, 100); 
}); 
+1

どうしたら入力名が「オプション」で始まらないのですか? –

+0

@AlexanderHein問題のコードを確認してください。すべての要素名は 'option'で始まります。 – Tushar

0

あなたはこれを試すことができます。

//I would rather use a class instead of just input but anyhow... 
$('input').change(function(){ 
    var elem_name = $(this).attr('name'); 
    $('#'+elem_name).addClass('highlight'); 
    setTimeout(function() { 
     $('#'+elem_name).removeClass('highlight'); 
    }, 100); 
}); 
関連する問題