$('#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 :(得分:5)
您可以通过this.id
获取调用更改的元素的ID。
$('#select_id1, #select_id2, #select_id3').change(function() {
str = this.id;
});
答案 1 :(得分:1)
或(效率较低):
$('#select_id1, #select_id2, #select_id3').change(function() {
str = $(this).attr("id");
});
但基本上this
设置为发生事件的元素。
答案 2 :(得分:1)
对于更一般的情况,不仅使用ID,如@Anurag所建议,您可以执行以下操作:
// 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
});
答案 3 :(得分:0)
您可以直接或通过传入的事件对象间接查看this.id
:
$('#select_id1, #select_id2, #select_id3').change(function (e) {
alert(e.target.id + ' == ' + this.id + ' ... ' + (e.target.id == this.id));
});
大多数人只看this
,但有时您可能不仅仅对您的活动目标感兴趣。