$(this)和这个内部点击事件

und*_*ned 3 jquery function this

我有一个自己的js-class并尝试在点击事件中使用jquery的$(this)和object-this.

jquery的$(this)工作正常,但是对象 - 这没有定义.

http://jsfiddle.net/j33Fx/2/

var myclass = function(){

    this.myfunction = function(){
        alert('myfunction');
    }

    this.buttonclicked = function(){
        alert('buttonclicked');
    }

    this.writeout = function(){
        var buttoncode = '<button class="mybutton">click</button>';
        $('body').append(buttoncode);

        $('.mybutton').click(function(){
            alert('Button: '+$(this).attr('class'));
            this.buttonclicked(); 
        });

        this.myfunction();
    }

}


var x = new myclass();
x.writeout();
Run Code Online (Sandbox Code Playgroud)

当我单击附加按钮时,我得到一个带有Button类名的警报,但我的函数"this.buttonclicked"似乎不是一个函数.

有任何想法吗?

Sat*_*pal 11

this是指在事件处理程序中调用事件的元素.您可以将当前对象缓存在其他变量中.哪个可以用于后者.

使用

this.writeout = function(){
    var buttoncode = '<button class="mybutton">click</button>';
    $('body').append(buttoncode);

    var _self = this; //cache current object

    $('.mybutton').click(function(){
        alert('Button: '+ $(this).attr('class')); //Here this refers to element which invoked the event.

        _self.buttonclicked(); //Use cached object
    });

    this.myfunction();
}
Run Code Online (Sandbox Code Playgroud)

更新小提琴

  • @JoseOspina,我不知道你的确切问题,但是你可以看看 [Function.prototype.bind()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects /函数/绑定) (2认同)