点击嵌套在按钮中的元素的事件 [英] Click event for Element nested within a Button

查看:122
本文介绍了点击嵌套在按钮中的元素的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的问题示例:

 < body> 
< button id =parentonclick =alert('parent')>
< span id =childonclick =alert('child')>身份验证< / span>
< / button>
< / body>

在Chrome中,此警告提示孩子,然后是父母,但在IE / FF中,父母。



显然,这可以通过很多方式解决(将按钮更改为div,删除span等),但我想知道是否有在不更改HTML的情况下使其工作的方式(即提醒孩子)。



谢谢!

PS :试过JQuery,它有相同的行为。正如@ muistooshort所说,处理其他点击事件中的点击事件看起来不自然。我也认为你必须重新考虑你的设计。



这就是说,你可以在主容器上处理一个单击事件,然后检查哪个元素是源的点击



考虑到您的使用情况,您可以选择以下方式:

  $('your-button-container')。click(function(event){
console.log(event.originalEvent.srcElement);
});

event.originalEvent.srcElement 并采取相应措施。

编辑:
不使用JQuery,它会像这样:

  yourButtonContainer.addEventListener(function(event){
console.log(event.srcElement);
});


Here is a simple example of the problem:

<body>
  <button id="parent"  onclick="alert('parent')">
      <span id="child" onclick="alert('child')">Authenticate</span>
  </button>
</body>

In Chrome this alerts "child" then "parent", but in IE/FF we only get "Parent".

Clearly this can be fixed in a number of ways (change button to div, remove span etc.), but I wanted to find out if there was a way to make this work (i.e. alert "child") without changing the HTML.

Thanks!

PS: Tried JQuery and that has same behaviour.

解决方案

As @muistooshort said, handling click events inside other click events seems unnatural. I also think you have to rethink your design.

That being said, you can handle a single click event on your main container and then check which element was the source of the click

This would be the way to go, considering your use case, imo:

$('your-button-container').click(function(event){
    console.log(event.originalEvent.srcElement);
});

Make the necessary checks on event.originalEvent.srcElement and act accordingly.

Edit: Not using JQuery, it would go like this:

yourButtonContainer.addEventListener(function(event){
    console.log(event.srcElement);
});

这篇关于点击嵌套在按钮中的元素的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆