2 回答

TA貢獻1836條經驗 獲得超4個贊
因此,您可以做很多事情來改進代碼。我將在這里做兩件事——首先,發布一些稍微改進的代碼,然后提供一些關于如何改進你自己的JavaScript. 涼爽的?
更新的代碼
const values = {};
function doItAll() {
for (let i = 1; i <= 8; i++) {
const UE = document.getElementById(`UECHECK${i}`).checked;
const GRA = document.getElementById(`GRADE${i}`).value;
const CRE = document.getElementById(`CREDITS${i}`);
const grades = ['A', 'M', 'E'];
if (UE === true || grades.some(GRA)) {
values[`UEAPPCRE${i}`] = CRE;
} else if (UE === false || grades.some(GRA)) {
values[`UEAPPCRE${i}`] = 0;
} else {
values[`UEAPPCRE${i}`] = 0;
values[`CRE${i}`] = 0;
values[`Missed${i}`] = CRE;
}
}
}
function testingItOut() {
const uECheckP = document.getElementById("UECheckP");
const totalCre = document.getElementById('TotalCre');
const totalMiss = document.getElementById('TotalMiss');
let totalUE = 0;
let totalCredits = 0;
let totalMissed = 0;
for (let i = 1; i <= 8; i++) {
totalUE += values[`UEAPPCRE${i}`];
totalCredits += values[`CRE${i}`];
totalMissed += values[`Missed${i}`];
}
uECheckP.innerHTML = `Passed: ${totalUE >= 14
? 'You have passed the university entrence of this subject.'
: (totalUE >= 100 || totalUE < 0)
? 'Please check your input of credits.'
: 'You have not passed the university entrence of this subject.'}`;
totalCre.innerHTML = `Credits: ${totalCredits > 0
? `You have gained ${totalCredits} credits in this subject.`
: 'Please check your input of credits.'}`;
totalMiss.innerHTML = `Missed: ${totalMissed > 0
? `You have missed ${totalMissed} credits in this subject.`
: 'Please check your input of credits.'}`;
}
function TheBigFunction() {
if (document.readyState === 'complete') {
doItAll();
testingItOut();
} else {
document.getElementById('error').innerHTML = "The document hasn't finished loading!";
}
}
因此,首先,您在使用var關鍵字的原始代碼中掌握了全局變量。我建議研究 ES6 語法(特別是let和const)scope、 和context。盡量遠離var聲明。
在更新后的代碼中,您將看到我使用 ES6 模板字面量來動態引用values對象變量,該對象變量“包含”具有您原始代碼使用的基本上所有變量的值的屬性。還要注意循環的使用——您有八個廣泛的元素和變量類別,因此不必將每一個都寫出來,我已經展示了如何動態引用它們。我還建議多看看你的邏輯(特別是doItAll函數)。
通常,JavaScript變量是使用 構造的camelCase,所以也看看它。遵循此約定將使您的代碼更具可讀性,尤其是當您要在 SO 上發布時。并且,至少在您的 HTML 中,請注意 ID 和類之類的內容傾向于遵循該kebab-case樣式。我知道,樣式太多了——當然,沒有什么是 100% 的,但大多數開發人員和公司傾向于堅持這些約定。
整個過程中都存在語法錯誤——你大寫了document大約 10 次左右,并且在隨后document.getElementById的左括號之前跟隨幾個s 和一個句點。小心那里!
就作用域而言,函數內聲明的變量不能在函數外訪問,至少不能直接訪問。因此,在您的UECreCheck函數中,您聲明了大約 24 個變量,然后嘗試在其余函數中直接進一步訪問它們的值。這些情況下的值將是undefined,這沒有幫助。
最后,雖然不是完全必要(取決于您的用例),但我添加了一個檢查TheBigFunction- 如果您的用戶(或您)TheBigFunction在文檔加載之前調用,各種基于 DOM 的變量分配基本上不會“看到" 頁面上的任何內容,因此您必須確保在引用 DOM 之前檢查內容是否已經ready或之后loaded。
同樣要回答您的原始問題,請盡量不要使用 HTML 屬性,例如onclick. 相反,在您的 HTML 文件中,刪除onclick屬性和函數調用,并將其添加到您的functions.js文件中:
window.onload = () => {
document.getElementById('the-button').addEventListener('click', e => {
e.preventDefault();
TheBigFunction();
});
};
我下來查找有關此進一步參與-這里的例子是不是最好的任何手段,但它表明你如何能簡化代碼,更新你的語法,等
添加回答
舉報