這個問題在這里已經有了答案: ES6 中的箭頭函式中的“this”指的是什么? (10 個回答) “箭頭函式”和“函式”是否等效/可互換? (4 個回答) 13 小時前關閉。
jquery 中的 .click 已棄用。所以我對現有代碼進行了修改,但是,似乎存在一些問題。
GetPageButtons() {
let $saveButton = $("<input />", {
type: "button",
value: "Save",
class: "button large save",
}),
$cancelButton = $("<input />", {
type: "button",
value: "Cancel",
class: "button large cancel",
});
$saveButton.click(() => {
this.UpdateRecord();
});
$cancelButton.click(() => {
this.modal.success = true;
let _parent = this;
$.each(_parent.fields, function (i, field) {
delete this.newValue;
this.element.val("");
});
});
return [$cancelButton, $saveButton];
}
上面的代碼有效,盡管我的 linter 抱怨說它已被棄用。
GetPageButtons() {
let $saveButton = $("<input />", {
type: "button",
value: "Save",
class: "button large save",
}),
$cancelButton = $("<input />", {
type: "button",
value: "Cancel",
class: "button large cancel",
});
$saveButton.on("click", function() {
this.UpdateRecord();
});
$cancelButton.on("click", function() {
this.modal.success = true;
let _parent = this;
$.each(_parent.fields, function (i, field) {
delete this.newValue;
$( this ).element.val("");
});
});
return [$cancelButton, $saveButton];
}
但是,對 .on('click', fn){} 建議使用的重構不起作用。我收到一條錯誤訊息:
"Uncaught TypeError: this.UpdateRecord is not a function".
Why? It should work the same as the .click which is shorthand for .on. Any suggestions???
uj5u.com熱心網友回復:
這不起作用,因為與使用箭頭函式的原始代碼相比,您使用的是普通函式。
這意味著this函式內部指的是不同的東西。
將其更改為
$saveButton.on("click", () => {
this.UpdateRecord();
});
$cancelButton.on("click", () => {
this.modal.success = true;
let _parent = this;
$.each(_parent.fields, function(i, field) {
delete this.newValue;
$(this).element.val("");
});
});
它應該像原來一樣作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/437462.html
標籤:jquery
