简体   繁体   中英

Behavior of removeEventListener

Please check the below code:

var clickfn = function(){
 alert("clicked");                    
}
document.getElementById("div1").addEventListener("click",clickfn,true);
clickfn = function(){  };
document.getElementById("div1").removeEventListener("click");

http://jsfiddle.net/qUtzL/4/

Why does the removeEventListener does not work?

removeEventListener takes 2 parameters, the event, and the function to remove.
This should work:

document.getElementById("div1").removeEventListener("click", clickfn);

Also, the function you're executing is empty.

var clickfn = function(){  };

You have to specify the exact function you've specified to addEventListener as the second argument. If you specified the third useCapture argument, you'll have to specify the same and equivalent to removeEventListener as well.

For example:

function myFunc(event){ alert(event.target.textContent); }

var myElement=document.getElementById('myElement');

//Add EventListener
myElement.addEventListener('click', myFunc, false );

/* ... */

//Remove EventListener
myElement.removeEventListener('click', myFunc, false );

View an example at jsFiddle

You can find more information at the Mozilla Developer wiki .

I recently had this issue with the Navbar code in ReactJS to give the Navbar a background color after scrolling 100px on the y-axis and remove it if the page view is within 100px of the top.

All I had to do is introduce a reverse function in the removeEventListener to give it the rules for application.

const [show, handleShow] = useState(false);
  useEffect(() => {
    window.addEventListener('scroll', () => {
      if (window.scrollY > 100) {
        // do this
        handleShow(true);
      } else handleShow(false);
    });
    return () => {
      window.removeEventListener('scroll', () => {
        if (window.scrollY < 100) {
          // do this
          handleShow(false);
        } else handleShow(true);
      });
    };
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM