jQuery event bubbling on button not working as expected in Firefox

橙三吉。 提交于 2019-12-06 20:50:44

问题


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


回答1:


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.




回答2:


Try changing

    <button> to <button type="button">

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.

     <script type="text/javascript">
        $(function() {
            $('button').click(function(){
                 return false
            });
        });
     </script>          

Hope this helps.

-D



来源:https://stackoverflow.com/questions/8187854/jquery-event-bubbling-on-button-not-working-as-expected-in-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!