我正在嘗試為具有各種配置頁面的應用程式創建一個模塊化的元素處理程式系列(例如:'Hex T' 配置具有元素'A'到'O',每個元素至少有1個DOM元素可以是以不同的方式修改,但“方墊”只有“A”到“E”,并且相同字母的元素并不總是指相同型別的元素,無論是下拉選單還是數字輸入)。
所以我所做的就是讓這樣的類LengthElement有 2 個數字輸入,一個用于英尺,一個用于英寸,因此LengthElement以英寸為單位保存值,然后每當元素之一(英尺或英寸)被更新時,它就會注冊更改為inches值,然后更改英尺和英寸元素以正確顯示正確的測量值(例如:10ft 0in => 10ft -1in => 9ft 11in)。
還有一個config陣列,其中包含應用程式可以具有的所有各種配置的串列,以及元素的順序和它們是什么。我將活動輸入標識為“輸入”,將禁用輸入標識為“框”,它只是幫助我保持直截了當。因此,“A”的 Hex T 活動輸入對將包含元素foot: '#ht-a-ft-input'和inch: '#ht-a-in-input'。我這樣做是為了不必多次寫出每個可能元素的所有 ID(目前僅此頁面上就有 100 多個)。
還有一個應用程式要求,其中某些長度必須能被 7 整除,我在這里有邏輯。它可能不相關,但我想我會把它包括在內,以防萬一。最后,有一個OnChange()函式被傳遞到每個物件實體中,這是一個帶有回呼的函式,它出現在其他地方,它作業得很好,所以我認為這并不重要。
這是整個類的代碼:
class LengthElement {
inches; //Value of the Two Elements in Inches
foot; //String of the Foot Element
inch; //String of the Inch Element
div7; //Flag to determine if change needs to be Divisible by 7
OnChange; //Function specific to the instance to be called whenever the input changes
constructor(i, cfg, abrv, oC) {
this.inches = i;
if (cfg.foot == 'input') {
this.foot = '#' abrv '-' cfg.name '-ft-input';
$(this.foot).on('input', this.InputVal);
}
else {
this.foot = '#' abrv '-' cfg.name '-ft-box';
}
if (cfg.inch == 'input') {
this.inch = '#' abrv '-' cfg.name '-in-input';
$(this.inch).on('input', this.InputVal);
}
else {
this.inch = '#' abrv '-' cfg.name '-in-box';
}
this.div7 = cfg.div7;
this.OnChange = oC;
}
GetFeet(i) {
return Math.floor(i / 12);
}
GetInches(i) {
return i % 12;
}
GetDiv7(i) {
if (i % 7 > 5) {
return i (7 - (i % 7));
}
else {
return i - (i % 7);
}
}
GetVal() {
return this.inches;
}
UpdateVal(i) {
if (this.div7) {
this.inches = this.GetDiv7(i);
}
else {
this.inches = i;
}
$(this.foot).val(this.GetFeet(this.inches));
$(this.inch).val(this.GetInches(this.inches));
}
InputVal() {
var newInches = ($(this.foot).val() * 12) $(this.inch).val();
var change = newInches - this.inches;
if (this.div7) {
if (change > 0) {
newInches = this.inches ((Math.floor(change / 7) * 7) 7);
}
else if (change < 0) {
newInches = this.inches - ((Math.floor(change / 7) * 7) 7);
}
else {
newInches = this.GetDiv7(newInches);
}
}
this.UpdateVal(newInches);
this.OnChange();
}
}
那么有什么問題呢?
每當InputVal()被呼叫時,this它指的是一個 jQuery 物件,而不是它所在的物件。我相信關鍵線是$(this.foot).on('input', this.InputVal);線,但我不確定它們到底有什么問題。
同樣,這是為了避免寫出每個元素的 ID 超過在 HTML 中宣告的一次,因此我可以使用任何替代方法來執行相同的任務。
我已經進行了大約 4 個月的單獨開發,所以我無法從 jQuery 中更改框架。我會得動脈瘤。
uj5u.com熱心網友回復:
您可以嘗試在建構式的頂部插入它
this.InputVal = this.InputVal.bind(this)
這樣thisInputVal 函式的內部總是指 LengthElement
uj5u.com熱心網友回復:
你應該宣告一個變數名的簡單技巧self,在你系結的建構式self = this中,在你可以使用的其他方法或回呼中,self而不是this
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/512797.html
上一篇:使用reduce洗掉陣列中的物件
下一篇:資料不一致的json
