Функциональность для всех допустимых номеров работает нормально. При использовании клавиш «нажатие» или «щелчок» преобразование римских цифр правильно отображается в выходном поле. Однако если то же самое делается для одного из номеров ошибок, поле вывода обновляется и отображает строку после следующего нажатия клавиши. Для чисел больше 3999 он также преобразует число и отобразит строку ошибки после следующего нажатия клавиши. Пожалуйста, проверьте мой код JS и дайте мне знать, если вы думаете.
Я все еще новичок в JS, поэтому любые другие идеи о том, как я могу улучшить свой код, также будут полезны.
p>
Код: Выделить всё
const numberInput = document.getElementById("number");
const convertBtn = document.getElementById("convert-btn");
const outputField = document.getElementById("output-field");
const resetBtn = document.getElementById("reset-btn");
const errorField = document.getElementById("error-field");
//conversion
function toRoman(num) {
const romanNumerals = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1
};
let result = "";
for (let i in romanNumerals) {
while (num >= romanNumerals[i]) {
result += i;
num -= romanNumerals[i];
}
}
return result;
}
//reset
function resetApp() {
outputField.textContent = "";
numberInput.value = "";
errorField.textContent = "";
}
//check user input
function inputCheck() {
const errorNum = parseInt(numberInput.value)
if (isNaN(errorNum) || !errorNum) {
outputField.textContent = "Please enter a valid number";
} else if (errorNum < 1) {
outputField.textContent = "Please enter a number greater than or equal to 1";
} else if (errorNum > 3999) {
outputField.textContent = "Please enter a number less than or equal to 3999";
} else {
outputField.textContent = "";
};
return;
}
//button functionality
convertBtn.addEventListener("click", () => {
inputCheck(numberInput.value);
outputField.textContent = toRoman(numberInput.value);
});
resetBtn.addEventListener("click", resetApp);
numberInput.addEventListener
("keydown", (e) => {
inputCheck(numberInput.value);
if (e.key === "Enter") {
outputField.textContent = toRoman(numberInput.value);
}
});
Код: Выделить всё
body {
font-family: system-ui;
text-align: center;
}
Код: Выделить всё
Convert
Output will appear here.
Reset
Errors will show here.
I've tried several fixes with .textContent, .value, .innerHTML, etc. this state is the best working I've had yet. When the outputField.textContent was replaced with errorField.textContent and displaying to a separate paragraph element the error messages worked great. However, that violates the code checks for the class as the error messages must display in the #output element.
Источник: https://stackoverflow.com/questions/779 ... e-late-ins