2010-12-13 7 views
2
$('#select_id1, #select_id2, #select_id3').change(function() { 
    // If '#select_id1' has changed, 'str' should be equal to 'select_id1'. 
    // If '#select_id2' has changed, 'str' should be equal to 'select_id2'. 
    // If '#select_id3' has changed, 'str' should be equal to 'select_id3'. 
    str = <what should be here ?> 
}); 
+0

あなたが変更ハンドラは、あなたがして、追加されたとのセレクターをしたい場合より多くの仕事をしなければならない。例えば、select要素がid - '$(" select1、#select2、div> .select3 ")以外の要素を使って選択できる場合です。 – Anurag

答えて

5

変更を呼び出す要素のIDはthis.idで取得できます。

$('#select_id1, #select_id2, #select_id3').change(function() { 
    str = this.id; 
}); 
1

以下(効率):

$('#select_id1, #select_id2, #select_id3').change(function() { 
    str = $(this).attr("id"); 
}); 

しかし、基本的にthisは、イベントが起こるの要素に設定されています。

+1

これを使う理由は本当にありません。 DOM属性を直接使用することは大いに非効率であり、推奨されません。 –

0

あなたは、イベントオブジェクトに渡さ経由で直接または間接的にthis.idで見ることができ、次のいずれか

$('#select_id1, #select_id2, #select_id3').change(function (e) { 
    alert(e.target.id + ' == ' + this.id + ' ... ' + (e.target.id == this.id)); 
}); 

ほとんどの人々はちょうどthisを見ていますが、あなただけのターゲットよりも多くのことに興味があるかもしれない時間がありますイベント。 @Anuragにより示唆されるように、あなたは次の操作を行うことができますだけではなくIDが使用されているより一般的なケースについては、

1

、:

// Save the selector 
var selector = ".someClass, #someId, tr.someTrClass"; 

$(selector).change(function() { 
    var selectors = selector.split(","), 
     matching = []; // Remember that each element can 
         // match more than one selector 
    for (var i = 0, s; s = selectors[i]; i++) { 
     if ($(this).is(s)) matching.push(s); 
    } 

    str = matching.join(","); // Your list of all matching selectors 
}); 
+0

一般的なコードを表示していただきありがとうございます! –

関連する問題