无法在 Polymer 中进行用户定义的函数调用
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 未定义。用箭头函数切换你的函数,它应该没问题,因为它会指向右边 class.
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);
};
我正在使用 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 未定义。用箭头函数切换你的函数,它应该没问题,因为它会指向右边 class.
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);
};