事件委托&jQuery on

例如:

<h2>Great Web resources</h2>

<ul id="resources">

  <li><a href="http://opera.com/wsc">Opera Web Standards

Curriculum</a></li>

  <li><a href="http://sitepoint.com">Sitepoint</a></li>

  <li><a href="http://alistapart.com">A List Apart</a></li>

  <li><a href="http://yuiblog.com">YUI Blog</a></li>

  <li><a href="http://blameitonthevoices.com">Blame it on the

voices</a></li>

  <li><a href="http://oddlyspecific.com">Oddly specific</a></li>

</ul>

最佳脚本书写方式:

原生js实现:

(function(){

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

  resources.addEventListener('click',handler,false);

  function handler(e){

    var x = e.target; // get the link tha

    if(x.nodeName.toLowerCase() === 'a'){

      alert('Event delegation:' + x);

      e.preventDefault();

    }

  };

})();

 jQ实现:

 //给列表绑定跳转链接
        bindJumpUrl: function(el){
            var self = this;
            el.on('click', 'a' , function(e) {
                e.preventDefault();
                e.stopPropagation();
                var href = $(this).attr("href");
                self.gotoActivityPage(href);
            });
        }

 遇到的一点小问题

var submitGoods = function(){
        console.log(this);//btn1,这是事件处理函数
        //这里就得不到window的this了。。只能传参传self。当然了,我们不用这种写法
    }
    $("#btn1").on("click",self,self.submitGoods);
var a = 1;
    var self = this;
    var getProductInfo = function(e, arg){
        console.log(this);//window,这样window上的方法我们这里就可以用了
        console.log(e);//j…y.Event
        console.log(a);//1
        console.log(arg);//要传到事件处理函数的参数
    };
    $("#btn1").on('click',function(e){
        console.log(this);//btn1,这是事件处理函数,这个函数的this是被点击的对象
        var arg = "要传到事件处理函数的参数";
        self.getProductInfo(e, arg);
    })//所以说这种方法是完美的
原文地址:https://www.cnblogs.com/darr/p/4650717.html