[英]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.