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

Stop Javascript event from affecting child elements - Stack Overflow

programmeradmin1浏览0评论

I have a script that creates an element, and part of the creation process is to add an onclick event (using addEventListener), but when I click a child element, the onclick event of the parent is triggered. How can I prevent the click from being detected when the source is a child element?

I have a script that creates an element, and part of the creation process is to add an onclick event (using addEventListener), but when I click a child element, the onclick event of the parent is triggered. How can I prevent the click from being detected when the source is a child element?

Share Improve this question asked Aug 20, 2012 at 18:47 tophergtopherg 4,3234 gold badges38 silver badges73 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

Use event.stopPropagation(). This stops the bubbling of Javascript events and will only allow the events applied to the targetted element to execute;

window.addEventListener("click", function(event){

    // event here

    event.stopPropagation();
}, false);

The problem is that the event is bubbling up to the parent.

In the child's onclick event, tell the event to stop propagation:

onclick = function (event) {
    // ...
    event.stopPropagation();
};

the parent click handler: (check on the id of the clicked element)

function handler(e){
  if(e.target.id != "parentID") return;
  ....
}
发布评论

评论列表(0)

  1. 暂无评论