patternjavascriptCritical
Getting the ID of the element that fired an event
Viewed 0 times
eventgettingtheelementfiredthat
Problem
Is there any way to get the ID of the element that fires an event?
I'm thinking something like:
Except of course that the var
I'm thinking something like:
$(document).ready(function() {
$("a").click(function() {
var test = caller.id;
alert(test.val());
});
});
Except of course that the var
test should contain the id "aaa", if the event is fired from the first form, and "bbb", if the event is fired from the second form.Solution
In jQuery
Note also that
event.target always refers to the element that triggered the event, where event is the parameter passed to the function. http://api.jquery.com/category/events/event-object/$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id);
});
});Note also that
this will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as $(this), e.g.:$(document).ready(function() {
$("a").click(function(event) {
// this.append wouldn't work
$(this).append(" Clicked");
});
});Code Snippets
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id);
});
});$(document).ready(function() {
$("a").click(function(event) {
// this.append wouldn't work
$(this).append(" Clicked");
});
});Context
Stack Overflow Q#48239, score: 1415
Revisions (0)
No revisions yet.