Missing click event for inside <button> element on firefox

后端 未结 4 1718
日久生厌
日久生厌 2020-11-28 15:41

I am experiencing problem with Firefox 32 when I bind action on click event of span element inside a button element. Other browsers seems to works well.

Here the cod

4条回答
  •  遥遥无期
    2020-11-28 16:04

    Working
    inside a button Not working

    What you actually want to do here is have a click event on the button - always the button, as that is the native HTML element and has built in accessibility for all.

    The reason your button click won't fire if you click on something wrapped in a span (or or etc) inside a button is because you are listening for a click on event.target (what's actually clicked) and not on event.currentTarget.

    If you want to listen to the button click itself (a click anywhere inside the button, including the span) you would use something like this:

    HTML:

    
    

    Javascript:

    const myButton = document.querySelector('.jsAlertOnClick');
    
    function handleBtnClick(event) {
      const btn = event.currentTarget;
      window.alert(btn + 'has been clicked!');
    }
    
    myButton.addEventListener('click', handleBtnClick);
    

    If you click on the span, that alert will fire first, followed by the button one. If you click elsewhere in the button, only that alert will fire.

提交回复
热议问题