【问题标题】:Append method to button created in other method in javascript将方法附加到在 javascript 中的其他方法中创建的按钮
【发布时间】:2017-03-06 19:17:29
【问题描述】:

可以在事件 onclik 中添加方法。此代码在 html "onclick='alert("TEST");undefined'" 中创建事件 onclick。我想得到 "onclick='alert("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/

【问题讨论】:

  • 用引号将this.stdaction(this.id) 括起来。

标签: javascript jquery object


【解决方案1】:

代替

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

写一些类似的东西

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

【讨论】:

  • 这是部分解决方案,因为控制台返回“this.stdaction is not a function”我改用jquery创建div元素到javascript并将Button.prototype.stdaction的定义移动到button .addEventListener 可以工作,想让我连接 Button.prototype.stdaction 事件的声明被剥离jsfiddle.net/uevckbe0
  • 我不知道 stdaction 是什么,它没有在你的代码中定义,所以我也没有定义它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-26
  • 1970-01-01
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
  • 2014-06-18
  • 1970-01-01
相关资源
最近更新 更多