javascript - 多次点击后,滚动事件问题~
PHPz
PHPz 2017-04-10 15:58:54
0
1
591

http://codepen.io/YuanWing/pen/XmaYbr

如果我把1,2,3都点了一下,然后滚动滚动条,内容追加了三次;

我都有removeEventListener,为什么不是只追加一次呢~

因为有参数传递,所以scrollFn只能定义到page里面~

<body>
    <p class="wrapper"></p>
    <ul class="tab-title" id="tabTitle">
        <li>click1</li>
        <li>click2</li>
        <li>click3</li>
    </ul>
    <p class="tab-con" id="tabCon"></p>
    <script>
        var tabTitle = document.getElementById('tabTitle');
        var tabCon = document.getElementById('tabCon');
        
        tabTitle.addEventListener('click', fn, false);
        
        function fn(e) {
            var _t = e.target;
            if(_t.tagName.toLowerCase() === 'li') {
                page({page: '__one__'});
            }
        }
        
        function page(obj){
            document.body.removeEventListener('scroll', scrollFn, false);
            document.body.addEventListener('scroll', scrollFn, false);
            
            function scrollFn() {
                document.body.removeEventListener('scroll', scrollFn, false);
                tabCon.innerHTML += obj.page;
            }

        }
        
    </script>
</body>
PHPz
PHPz

学习是最好的投资!

reply all(1)
刘奇

每次page执行的时候,
定义的scrollFn都是一个新的内部函数值
那么就导致document.body.removeEventListener('scroll', scrollFn, false);实际上是没有效果的
那么代码可以如下修改

function fn(e) {
    var _t = e.target;
    if(_t.tagName.toLowerCase() === 'li') {
        page({page: '__one__'});
    }
 }

var scrollFunObj=(function(){
    var obj;
    return {
      setObj:function(objIn){
        obj=objIn;
      },
      scrollFn:function(){
      
         tabCon.innerHTML += obj.page;
      }
    }
})();

function page(obj){
    scrollFunObj.setObj(obj);
    document.body.removeEventListener('scroll', scrollFunObj.scrollFn, false);
    document.body.addEventListener('scroll', scrollFunObj.scrollFn, false);
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!