2016-01-21 148 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'); 
    } 
} 
相關問題