当前位置: 代码迷 >> 综合 >> JavaScript 的 addEventListener 与 removeEventListener
  详细解决方案

JavaScript 的 addEventListener 与 removeEventListener

热度:56   发布时间:2024-01-05 05:00:07.0

最近使用JS监听命令时,发现了很多知识点不足,在此整理一下。

正确用法

//禁止动作
function noScroll(e){
    e.preventDefault();
}
//添加事件
document.addEventListener('touchmove',noScroll,false);
//接触绑定
document.removeEventListener('touchmove',noScroll,false);

错误用法⑴

function noScroll(e){
    e.preventDefault();
}
document.addEventListener('touchmove',noScroll(e),false);
document.removeEventListener('touchmove',noScroll(e),false);

共用一个noScroll方法,不能带参数。


错误用法⑵

document.addEventListener('touchmove', function(e){
    e.preventDefault();},false);
document.removeEventListener('touchmove', function(e){
    e.preventDefault();},false);

添加事件和解除绑定要使用同一个Function,否则不能成功解绑。

  相关解决方案