将方法附加到javascript中以其他方法创建的按钮

时间:2017-03-06 19:17:30

标签: javascript jquery object

可以为事件onclik添加方法。此代码创建事件onclick in html" onclick =' alert(" TEST"); undefined'"。我很关心" onclick ='警告(" TEST"); stdaction(' t1')'" stdaction(' t1')在类Button中的功能

function Button(id,onclick){
        this.id = id;
        this.onclick= onclick;
    }

Button.prototype.create = function(){
    var button = $('<div>');
    button.attr('id',this.id);
    button.html('Default');
    button.attr('onclick',this.onclick+';'+this.stdaction(this.id)); // this is problem
    return button.prop('outerHTML');
}

Button.prototype.stdaction = function(id){
    $('#'+id).addClass('std-active');
}
var oneButton = new Button('t1','alert("TEST")');
$('#newButton').append(oneButton.create());

我按照建议更改了Paflow更好,但是我想让一个函数连接运行onclick,即使有一个单独的方法 https://jsfiddle.net/uevckbe0/

1 个答案:

答案 0 :(得分:0)

而不是

   button.attr('onclick',this.onclick+';'+this.stdaction(this.id)); // this is problem

写点像

  button.addEventListener('click', function() {
     this.onclick();
     this.stdaction(this.id)
  }.bind(button));