[英]Unable to make user defined function call in Polymer
我正在使用Polymer 3.0实现我的网站。 我正在javascript 中创建按钮。 我想在单击按钮时调用用户定义的函数。
我曾尝试添加事件侦听器,但该函数在页面加载后立即被调用。 我尝试在 bu.onclick 函数中调用该函数,但该函数没有被调用
//我的代码如下
import { PolymerElement, html } from "./node_modules/@polymer/polymer/polymer-element.js";
class MyPage extends PolymerElement {
static get template() {
return html`
<!-- Some useful div elements -->
<iron-ajax
auto
url= // my url
handle-as="json"
on-response="response"
on-error="_statusFailed"
last-error="{{lastError}}"
last-response="{{lastResponse}}"
debounce-duration="300">
</iron-ajax>
`;
}
constructor()
{
super();
}
response()
{
let list = this.shadowRoot.querySelector('#list');
let bu = document.createElement('button');
bu.onclick=function()
{
let a= this.value;
console.log('Button Value: '+a);
this.buttonprocessor(a);
};
list.append(bu);
}
buttonprocessor(msg)
{
//some code
}
当我单击创建的按钮时,出现以下错误
Uncaught TypeError: this.buttonprocessor is not a function
at HTMLButtonElement.bu.onclick
先谢谢了。
我认为错误消息指向正确的方向 this.buttonprocessor 未定义。 用箭头函数切换你的函数,应该没问题,因为这将指向正确的类。
bu.onclick=() => {
let a= this.value;
console.log('Button Value: '+a);
this.buttonprocessor(a);
};
函数状态中的 this 始终指向函数本身,您也可以这样解决:
var that = this;
bu.onclick=function()
{
let a= this.value;
console.log('Button Value: '+a);
that.buttonprocessor(a);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.