jQuery event bubbling on button not working as exp

2019-04-20 07: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

2条回答
相关推荐>>
2楼-- · 2019-04-20 08:30

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.

查看更多
ら.Afraid
3楼-- · 2019-04-20 08:39

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

查看更多
登录 后发表回答