Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery';在';未将事件绑定到元素_Javascript_Jquery - Fatal编程技术网

Javascript jQuery';在';未将事件绑定到元素

Javascript jQuery';在';未将事件绑定到元素,javascript,jquery,Javascript,Jquery,我有以下函数,它被立即调用并将单击事件绑定到元素 (function (window, $, undefined) { var methods = {}, selector = $('.selector'); methods.init = function () { selector.find('> .section').on('click', function (e) { alert('hey');

我有以下函数,它被立即调用并将单击事件绑定到元素

(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函数已经运行,但是click事件没有触发?

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

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

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

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