我正在尝试使用 Poylmer 2.x 中的函数将 paper-button
动态附加到 DOM。
我希望这个新按钮在点击时调用另一个函数。
appendNodeToDom() {
let prop = this.result[i]['someProperty'];
let node = document.createElement("paper-button");
let button = document.createTextNode(prop);
button.ontap = this.go(); // what is the proper syntax for this?
node.appendChild(button);
this.shadowRoot.getElementById('buttons').appendChild(node);
}
go() {
console.log('go');
}
还尝试过:
button.addEventListener("click", this.go());
button.addEventListener("tap", this.go());
如何在 Polymer 2.x 中使用 Javascript 设置“点击”行为?
最佳答案
问题是您正在paper-button
内部调用button
文本节点,并在该节点上设置事件监听器 -作为 Text
节点 - 不会触发事件(除了一些 exceptions )。
此外,您还将 this.go()
作为回调传递给 addEventListener
。这意味着 this.go()
被执行,然后返回值作为回调传递(在本例中为 undefined
因为在 console.log 之后你不会返回任何东西)。您应该传递函数的标识符而不调用它:
addEventListener('tap', this.go);
一起:
appendNodeToDom() {
let prop = this.result[i]['someProperty'];
let button = document.createElement('paper-button');
let text = document.createTextNode(prop);
button.appendChild(text);
button.addEventListener('tap', this.go); // Add the listener to button
this.shadowRoot.getElementById('buttons').appendChild(node);
}
go() {
console.log('go');
}
<小时/>
请注意:请记住,Polymer 有很多工具可以避免执行直接 DOM 操作。如果您只需要向列表添加一个按钮,您可以考虑使用 dom-repeat 呈现按钮并在底层数组属性上进行更改的解决方案。
关于javascript - 如何在 Polymer 中使用 Javascript 设置 `on-tap` </paper-button> 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54790242/