点击嵌套在按钮中的元素的事件 [英] Click event for Element nested within a Button
问题描述
这是一个简单的问题示例:
< 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);
});
对 编辑: Here is a simple example of the problem: 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: Make the necessary checks on Edit:
Not using JQuery, it would go like this:
这篇关于点击嵌套在按钮中的元素的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! event.originalEvent.srcElement $ c $进行必要的检查c>并采取相应措施。
不使用JQuery,它会像这样:
yourButtonContainer.addEventListener(function(event){
console.log(event.srcElement);
});
<body>
<button id="parent" onclick="alert('parent')">
<span id="child" onclick="alert('child')">Authenticate</span>
</button>
</body>
$('your-button-container').click(function(event){
console.log(event.originalEvent.srcElement);
});
event.originalEvent.srcElement
and act accordingly.yourButtonContainer.addEventListener(function(event){
console.log(event.srcElement);
});