开发者

Show ID for image clicked

开发者 https://www.devze.com 2023-03-03 19:07 出处:网络
My HTML is like so: <img src=\"/path\" id=\"img_1\"> 开发者_如何学编程<img src=\"/path\" id=\"img_2\">

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);" />
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号