方法 1: 行ごとの閉鎖
ここにフィドルがあります
each 関数を使用して各行のクロージャを作成することができます。この場合、各行には独自の変更された変数があります。
また、入力要素に直接バインドするのではなく、on() jQuery 関数を使用して、イベント リスナーを間接的にバインドできます。
注:入力は、行要素から直接離れた子ではないため、children()をfind()と交換します。
$( document ).ready(function() {
// Using the each function to create
// a row specific closure
$('.vraagrij').each(function() {
// Track the state per row
var changed = false
// Create a variable to reference the
// row directly in the change listener
, $row = $(this);
// Use event delegation to bind to all
// descendant selects of the row efficiently
$row.on("change", "select", function(e) {
// Make sure the following only runs once
// per row
if(!changed) {
changed = true;
// Do something to the input, changing
// color for testing purposes
var $kids = $row.find("input");
$kids.css('color', 'yellow');
}
});
});
});
方法 2: DOM クエリ / トラバーサル
別のフィドル
このメソッドは、DOM の状態を使用して、変更された状態を追跡します。
$(document).ready(function() {
// Again using event delegation to bind events
// efficiently
$(".vraagrij").on("change", "select", function(e) {
// Collect the parent row
var $row = $(this).closest("tr");
// Check if it has already got the
// changed class
if(!$row.hasClass("changed")) {
// Add the changed class in to track
// the state and prevent this being
// run again for the same row
$row
.addClass("changed")
// Perform the action for the changed
// select
.find("input")
.css("color", "yellow");
}
});
});
方法 3: 1 つの方法を使用する
別のフィドル
one メソッドは、イベントを 1 回処理します。
またはの代わりに使用するビリオネカンからの素晴らしいアドバイスを含む更新closest("tr")
parents("tr:eq(0)")
parents("tr").first()
$(document).ready(function() {
// Again using event delegation to bind events
// efficiently, this time using the one method
$(".vraagrij").one("change", "select", function(e) {
// Perform the action for the changed
// select
$(this).closest("tr").find("input").css("color", "yellow");
});
});