Reputation: 28284
My HTML is like so:
<img src="/path" id="img_1">
<img src="/path" id="img_2">
<img src="/path" id="img_3">
<img src="/path" id="img_4">
I want to alert out the id of the button that was clicked.
How can I accomplish that?
Upvotes: 1
Views: 10764
Reputation: 146302
$('img').click(function(){
alert(this.id);
}); //try that :-)
Or a more 'dynamic version' (if you are adding the images by ajax or some other implementation):
$('img').live('click', function(){
alert(this.id);
}); //try that :-)
Upvotes: 5
Reputation: 19609
With jQuery:
$('img').click(function() {
alert($(this).attr('id'));
});
Or plain JS:
function handleClick(sender) {
alert(sender.id);
}
<img src="/path" id="img_1" onclick="handleClick(this);" />
<img src="/path" id="img_2" onclick="handleClick(this);" />
<img src="/path" id="img_3" onclick="handleClick(this);" />
<img src="/path" id="img_4" onclick="handleClick(this);" />
Upvotes: 2
Reputation: 4288
$("img").click(function() {
alert($(this).attr("id"));
});
Upvotes: 4