Click event on button is sending an icon as the target?

前端 未结 5 1469
走了就别回头了
走了就别回头了 2020-12-24 07:17

I am having an issue very similar to: \"Jquery \'click\' not firing when icon is on button\" however the resolution for that post is not providing a solution for me, so I th

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-24 08:16

    update this because $(event.target) is not always button for this you have to use ternary operator as suggested or replace $(event.target) with $(this) which is always button in the context of selector:

    function sendVote(event) {
        event.stopPropagation(); 
        var $btn = $(event.target).is('button') ? $(event.target) : $(event.target).parent();
        console.log(parseInt($btn.data('vote')));
        console.log($btn.prop('tagName'));
    }
    $(function () {
        $('body').on('click','button.vote-button', sendVote);
    });
    

    Demo fiddle


    or with $(this) which is always button because the event is bound to it and if you click on any child of it then event will bubble up to the dom tree and event bound to button gets executed:

    function sendVote(event) {
        var $btn = $(this);  // <-----------------change just here
        console.log(parseInt($btn.data('vote')));
        console.log($btn.prop('tagName'));
    }
    

提交回复
热议问题