按钮上的 jQuery 事件冒泡在 Firefox 中无法按预期工作
我有一个
HTML
<button>
<span>Text1</span>
<span>Text2</span>
</button>
Javascript
$(function() {
$('button').bind('click', function() {
console.log('button clicked');
});
$('button > span:eq(0)').bind('click', function() {
console.log('text1 span clicked');
});
$('button > span:eq(1)').bind('click', function() {
console.log('text2 span clicked');
});
});
这在 Chrome 中一切正常,并且点击事件以正确的顺序捕获:首先在任何 span 元素上然后事件向上冒泡到父按钮元素。
问题是,在 Firefox 中,任何 span 元素都不会触发 click 事件,只是按钮事件处理程序将事件记录为已触发。
这是一个小提琴,这样你就可以明白我的意思: http://jsfiddle.net/spider/RGL7a/2/
谢谢
I have a <button>
element inside of which I have 2 <span>
elements. I have 2 attached jquery click event handlers for each of the span elements so I can do whatever I like for each click. Here's a quick look of the basic code:
HTML
<button>
<span>Text1</span>
<span>Text2</span>
</button>
Javascript
$(function() {
$('button').bind('click', function() {
console.log('button clicked');
});
$('button > span:eq(0)').bind('click', function() {
console.log('text1 span clicked');
});
$('button > span:eq(1)').bind('click', function() {
console.log('text2 span clicked');
});
});
This is all working fine in Chrome and the click event is captured in the correct order: first on any of the span elements and then the event bubbles up to the parent button element.
The problem is that in Firefox the click event does not fire for any of the span elements, just the button event handler logs the event as being fired.
Here's a fiddle so you can see what I mean: http://jsfiddle.net/spider/RGL7a/2/
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个简单的解决方案是使用
元素而不是按钮元素。将要触发的通用代码放入函数中,然后在单击任一跨度以及该跨度的唯一代码时执行该函数。如果您想更加符合 508,您可以将跨度放入
标记(甚至
显然,这并不能解释 FF事件处理,但这可能是一种更快的方法。
A simple solution would be to use a
<div>
element instead of a button element. Put the common code you want fired into a function and then execute the function when either of the spans are clicked as well as the span's unique code. If you wanted to be more 508 compliant you could make the spans into<a>
tags (or even<button>
tags.Obviously, that doesn't explain FF event handling but it might be a quicker way to go.
尝试更改
这应该可以立即解决您的问题。它不起作用的原因是它遵循按钮的默认操作,即提交。即 BUTTON 需要在 JavaScript 中返回 false 才能读取您的点击。就像您尝试单击链接而不将其默认操作设置为返回 false 一样。
如果您将以下 jQuery 代码行添加到您的 js,这也应该可以解决您的问题。确保在按钮 > 之前添加代码单击“绑定”。
希望这有帮助。
-D
Try changing
This should solve your issue off the bat. The reason its not working is because its following through with the default action of a button, which is to submit. i.e. BUTTON would need return false in the javascript for it to read your click. Just as if you were to try and click on a link without setting its default action to return false.
If you add the following line of jQuery code to your js, this should also resolve your issue. Make sure to add the code before your button > span click bind.
Hope this helps.
-D