$('#select_id1, #select_id2, #select_id3').change(function() {
// If '#select_id1' has changed, 'str' should be equal to 'sele开发者_JAVA百科ct_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 ?>
});
You can get the id of the element that invoked the change by this.id
.
$('#select_id1, #select_id2, #select_id3').change(function() {
str = this.id;
});
Or (less efficiently):
$('#select_id1, #select_id2, #select_id3').change(function() {
str = $(this).attr("id");
});
But basically this
is set to the element on which the event took place.
For the more general case, where not only IDs are used, as suggested by @Anurag, you can do the following:
// 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
});
You can either look at this.id
directly or indirectly via a passed in event object:
$('#select_id1, #select_id2, #select_id3').change(function (e) {
alert(e.target.id + ' == ' + this.id + ' ... ' + (e.target.id == this.id));
});
Most people just look at this
but there are times when you might be interested in more than just the target of your event.
精彩评论