1

Is it possible to define a on click event inside an object (oop)? I'm new to this. I have been trying the following: (I simplified the code (no CSS of div etc))

function menu_item(menu_name){
    this.menu_name=menu_name;

    this.create = function(){
        $('body').html("<div id=" + menu_name + " />");
    };  
    
    $('#' + menu_name).on('click',function(){
        alert (menu_name);
    });
}

menu_item("test");
menu_item.create();

Now when I click on the div with id of the given menu_name, I want to alert the name (as a test) but this isn't working... is this even possible?

4

1 回答 1

2

对的,这是可能的。但是,我在您的代码中看不到任何 OOP 构造函数 - 您将其称为函数。

您的问题似乎是当您尝试添加事件侦听器时没有具有该 id 的元素,或者对您的create方法的调用会覆盖它。

用这个:

function MenuItem(name){
    this.menu_name = name;

    this.create = function() {
        var el = $("<div id=" + menu_name + " />");
        el.on('click',function(){
            alert (menu_name);
        });
        $('body').append(el);
    };
}

var menu = new MenuItem("test");
menu.create();
于 2012-10-01T11:33:58.847 回答