嗨,羅伊爾(Rohail)只是在說些什么。 並非所有代碼都需要進入事件偵聽器塊,只是文檔引用即可。 例如,這是一個簡單的攝氏/華氏轉換器:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Celsius Fahrenheit Converter</title>
<script src="57641159.js"></script>
</head>
<body>
<div>
F: <input type="number" id="fahr" min="-459.67" step="0.01">
C: <input type="number" id="cels" min="-273.15" step="0.01">
</div>
</body>
</html>
在javascript注釋中,只有與讀取DOM相關的代碼才需要在已加載事件內。 這有助於使代碼保持簡單。
const round1 = x => Math.round(x * 10) / 10;
const updateC = () => {
const c = (fahr.value - 32) * (5/9);
cels.value = round1(c);
};
const updateF = () => {
const f = cels.value * (9/5) + 32;
fahr.value = round1(f);
};
const doDom = () => {
const fahr = document.querySelector('#fahr');
fahr.addEventListener('input', updateC);
const cels = document.querySelector('#cels')
cels.addEventListener('input', updateF);
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
doDom();
});
} else {
doDom();
}