最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Finding the source of a click in event bubbling - Stack Overflow

programmeradmin5浏览0评论

I have the following code:

<div id="buttons">
    <button id="btn1">1</button>
    <button id="btn2">2</button>
</div>

I attach an event handler to the <div> to handle clicks.

When I click a button, the event is captured by the div. Is there a way to get the source of the event?

For example, if the event were on each of the the buttons then the this keyword would refer to the buttons. When it's on the <div> it refers to that.

When the click is caught by the div, is there a way to locate the source of the click? i.e. which actual button was clicked?

Thanks all

Dave

I have the following code:

<div id="buttons">
    <button id="btn1">1</button>
    <button id="btn2">2</button>
</div>

I attach an event handler to the <div> to handle clicks.

When I click a button, the event is captured by the div. Is there a way to get the source of the event?

For example, if the event were on each of the the buttons then the this keyword would refer to the buttons. When it's on the <div> it refers to that.

When the click is caught by the div, is there a way to locate the source of the click? i.e. which actual button was clicked?

Thanks all

Dave

Share Improve this question edited Jul 28, 2017 at 18:05 BanksySan asked Apr 24, 2013 at 14:00 BanksySanBanksySan 28.6k36 gold badges125 silver badges230 bronze badges 1
  • Duplicate: stackoverflow./questions/485453/… – Vimal Stan Commented Apr 24, 2013 at 14:08
Add a ment  | 

2 Answers 2

Reset to default 5

You can use the originalTarget property of the event object to find out the source of the event.

JSFiddle

HTML

<div id="buttons">
    <button id="btn1">1</button>
    <button id="btn2">2</button>
</div>

JavaScript

document.getElementById('buttons').onclick = function (evt) {
    var source = evt.srcElement || evt.originalTarget
    alert(source.id);
}

If you use jQuery, this should help:

$("#buttons").click(function(evt){
       alert($(evt.target).attr("id"));
});
发布评论

评论列表(0)

  1. 暂无评论