简体   繁体   English

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

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

I'm trying to create a Object class that will take data and create a list of elements. 我正在尝试创建一个Object类,该类将获取数据并创建元素列表。 I also want to attach a click event on the new LI's that fires a method of the class. 我还想在新的LI上附加一个click事件,以触发该类的方法。 However, when using the 但是,当使用

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

this no-longer references the Class, so clicking on the li gives you an undefined method error. this不再引用该类,因此单击li会给您带来未定义的方法错误。 Suggestions on how to attach the class method to the newly create elements? 关于如何将class方法附加到新创建的元素上的建议?

JS Code: 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/ 小提琴: http : //jsfiddle.net/kmfstudios/EwC3r/5/

In order to make your method work in the click function, just reference your global variable that contains the object. 为了使您的方法在click函数中起作用,只需引用包含该对象的全局变量即可。

The line: 该行:

    this.show_clicked(i);

should be changed to: 应该更改为:

   base.show_clicked(i);

If you want your index value to be displayed in the final result, you'll have to either pass that as data, or use jquery to determine which index was clicked. 如果您希望索引值显示在最终结果中,则必须将其作为数据传递,或者使用jquery确定单击了哪个索引。

Here is an updated fiddle that works - http://jsfiddle.net/EwC3r/4/ 这是一个有效的更新小提琴-http: //jsfiddle.net/EwC3r/4/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM