2016-01-21 87 views
0

我有以下函数,它立即被调用并将一个click事件绑定到元素。jQuery'on'没有绑定元素的事件

(function (window, $, undefined) { 
    var methods  = {}, 
    selector = $('.selector'); 

    methods.init = function() { 
     selector.find('> .section').on('click', function (e) { 
      alert('hey'); 
     } 
    } 

    if (selector.length > 0) { 
     methods.init(); 
    } 

}(window, jQuery)); 

我需要它也结合已被动态地添加元素,所以我改成这样:

var modules = modules || {}; 
modules.stuff = (function (window, $, undefined) { 
    var methods  = {}, 
    selector = $('.selector'); 

    methods.init = function() { 
     selector.find('> .section').on('click', function (e) { 
      alert('hey'); 
     } 
    } 

    if (selector.length > 0) { 
     methods.init(); 
    } 


    return methods; 

}(window, jQuery)); 

,然后添加动态元素,然后叫modules.stuff.init();我可以看到,init函数跑了,但点击事件不会触发?

回答

3

您需要使用on()方法的委托签名。试试这个:

methods.init = function() { 
    selector.on('click', '> .section', function (e) { 
     alert('hey'); 
    } 
}