jQuery:如何将事件附加到类内新创建的元素

jQuery: How to attach an event to newly created element inside class

本文关键字:新创建 创建 元素 事件 jQuery      更新时间:2023-11-06

我正在尝试创建一个Object类,该类将获取数据并创建元素列表。我还想在激发类的方法的新LI上附加一个点击事件。但是,当使用时

el.click(function() {
    this.method();
});

this不再引用Class,因此单击li会出现未定义的方法错误。关于如何将类方法附加到新创建的元素的建议?

JS代码:

if (typeof Object.create !== 'function') {
    Object.create = function(o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
var base = {
    init: function(data) {
        this.data = data;
        this.show_data();
    },

    show_data: function() {
        for (i = 0; i < this.data.bindings.length; i++) {
            var $item = $('<li>' + this.data.bindings[i].ircEvent + '</li>');
            $item.click(function() {
                this.show_clicked(i);
            });
            $('#it').append($item);
        }
    },
    show_clicked: function(index) {
        console.log('clicked in method');
    }
};
var extended = {
    show_alert: function() {
        alert('second class');
    }
};

var myObj = {
    "bindings": [
        {
        "ircEvent": "PRIVMSG",
        "method": "newURI",
        "regex": "^http://.*"},
    {
        "ircEvent": "PRIVMSG",
        "method": "deleteURI",
        "regex": "^delete.*"},
    {
        "ircEvent": "PRIVMSG",
        "method": "randomURI",
        "regex": "^random.*"}
    ]
};
$(document).ready(function() {
    var baseObj = Object.create(base);
    baseObj.init(myObj);
});

Fiddle:http://jsfiddle.net/kmfstudios/EwC3r/5/

为了使方法在click函数中工作,只需引用包含对象的全局变量即可。

线路:

    this.show_clicked(i);

应更改为:

   base.show_clicked(i);

如果希望索引值显示在最终结果中,则必须将其作为数据传递,或者使用jquery来确定单击了哪个索引。

这是一个更新的小提琴,工作-http://jsfiddle.net/EwC3r/4/