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?
$('img').click(function(){
alert(this.id);
}); //try that :-)
DEMO
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 :-)
$("img").click(function() {
alert($(this).attr("id"));
});
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);" />
精彩评论