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

html - javascript nested onclick - Stack Overflow

programmeradmin1浏览0评论

I have this code:

<td onclick="Test()">
  <img src="test.jpg" onclick="Test2(); return false;"><br>
  Rest of the cell with some text.
</td>

When I click the image, Test() is also fired because I am also clicking the table cell. How to provent this? If I click on the image, I want test2() to fire, if I click somewhere else in the table cell, test() should be fired.

Edit: Even with return false, Test() is still fired(testing in Chrome)!

I have this code:

<td onclick="Test()">
  <img src="test.jpg" onclick="Test2(); return false;"><br>
  Rest of the cell with some text.
</td>

When I click the image, Test() is also fired because I am also clicking the table cell. How to provent this? If I click on the image, I want test2() to fire, if I click somewhere else in the table cell, test() should be fired.

Edit: Even with return false, Test() is still fired(testing in Chrome)!

Share Improve this question edited Mar 24, 2013 at 22:20 Mbrouwer88 asked Mar 24, 2013 at 22:11 Mbrouwer88Mbrouwer88 2,3024 gold badges28 silver badges38 bronze badges 1
  • learn about event delegation – tereško Commented Mar 29, 2013 at 10:44
Add a ment  | 

3 Answers 3

Reset to default 6

If Test2() returns false the click won't bubble to Test()

Short answer:

<img src="test.jpg" onclick="Test2(); return false;">

Long answer:

Event Order - http://www.quirksmode/js/events_order.html

The way I prefer is using eventListeners and event.stopPropagation() as I've read some browsers do not accept return false and it's also not a very well defined action. And like Adam said, it's worth it to read up on event propagation.

<div id="clickme"></div>

<script>
document.getElementById("clickMe").addEventListener("click", function(event) {
  event.stopPropagation();
  //event.preventDefault();  this is the same as return false;
});
</script>
发布评论

评论列表(0)

  1. 暂无评论