【问题标题】:ECMA Class - Return HTML and fire (class) functionECMA 类 - 返回 HTML 并触发(类)函数
【发布时间】:2018-01-25 13:38:34
【问题描述】:


也许这是不可能的,但我充满希望。

我正在尝试学习 ECMA 6,并且刚刚参加了“课程”。现在我的班级返回一些带有按钮的 HMTML getHTML()。现在我正在尝试绑定一个事件并触发另一个函数。

getHTML() {
    return `
        <button id="${ this.getId(false) }" class="btn btn-default" 
        onclick="${ this.setActive()}">${ this.getName() }</button>
    `
}

我想要启动的第二个函数如下所示:

setActive() { 
    this.getActive() ? this.isActive = false : this.isActive = true;
    alert(this.getActive()); 
}

oncklick = ... 是我的尝试,但它确实有效(谁会想到呢?)。

有没有机会让它发挥作用?

【问题讨论】:

  • 您的帖子中没有太多代码,但我猜是bind 问题。尝试bind 构造函数this.getActive = this.getActive.bind(this) 中的方法。或使用箭头函数,它将为 this 关键字使用词汇上下文:getHTML = () =&gt; {...} setActive = () =&gt; {...}
  • 不要使用 HTML 字符串。创建 DOM 元素并正确安装事件处理程序!
  • 为我工作,谢谢。

标签: javascript jquery ecmascript-6


【解决方案1】:

您正在有效地返回一个字符串。

`<button onClick="${this.doSomething()}"></button>`

将直接调用this.doSomething(),并将返回值.toString()插入结果中。

例子:

function test () { console.log('###') }

const f = `test=${test()}`

// logs ###

console.log(f) //"test=undefined"

我猜你想在 Button 上添加一个事件监听器,但是你需要先把 String 变成一个 DOM 节点。

【讨论】:

  • 我刚刚创建了一个元素,添加了事件监听器并返回了我的元素,现在一切正常,也谢谢你。
猜你喜欢
  • 2015-12-16
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
  • 2018-01-17
  • 1970-01-01
  • 2021-08-06
  • 1970-01-01
相关资源
最近更新 更多