代码在这里:
https://codepen.io/AthreyuIV/pen/EaYRRrb
const checkButton = document.getElementById("check-btn");
const textInput = document.getElementById("text-input")
const resultText = document.getElementById("result");
const formData = document.getElementById("palindrome");
checkButton.addEventListener("click", () => {
const cleanString = textInput.value.replace(/\W|_/g, "");
const reverseString = cleanString.split("").reverse().join("");
if (textInput.value === "") {
alert("Please input a value.")
} else if (reverseString.toLowerCase() === cleanString.toLowerCase()) {
resultText.textContent = `${textInput.value} is a palindrome`;
} else {
resultText.textContent = `${textInput.value} is not a palindrome`
}
formData.reset()
});
<link href="https://fonts.googleapis.com/css2?family=Rock+Salt&display=swap" rel="stylesheet">
<div class="wrapper">
<div class="checker-container">
<h1>Palindrome Checker</h1>
<p>Palindrome</p>
<p>Checker</op>
<form name="palindrome" id="palindrome">
<div class="input-container">
<input id="text-input" type="text">
<button id="check-btn" type="submit">Check</button>
</div>
</form>
<div class="results-container">
<span id="result"></span>
</div>
</div>
重置表单后,表单元素没有立即运行。好像变成残疾了。
我尝试使用 .refocus() 并尝试设置 textInput.disabled = false;我清除表格之前和之后。我什至尝试不使用 .reset() ,而是将 textContent 设置为空字符串。我尝试在 eventListener 之外创建一个重置函数,并将其作为函数调用。我尝试将只读更改为 false。
使用提交事件,然后调用
e.preventDefault();
来停止表单提交。
一般来说,在这种情况下你不需要所有的全局变量。使用
e.target
又名。表单作为参考并使用点符号来获取输入元素 (e.target.text_input
)。
const formData = document.forms.palindrome;
formData.addEventListener("submit", e => {
e.preventDefault();
const cleanString = e.target.text_input.value.replace(/\W|_/g, "");
const reverseString = cleanString.split("").reverse().join("");
if (e.target.text_input.value === "") {
alert("Please input a value.")
} else if (reverseString.toLowerCase() === cleanString.toLowerCase()) {
e.target.result_text.textContent = `${e.target.text_input.value} is a palindrome`;
} else {
e.target.result_text.textContent = `${e.target.text_input.value} is not a palindrome`
}
e.target.reset()
});
<link href="https://fonts.googleapis.com/css2?family=Rock+Salt&display=swap" rel="stylesheet">
<div class="wrapper">
<div class="checker-container">
<h1>Palindrome Checker</h1>
<p>Palindrome</p>
<p>Checker</op>
<form name="palindrome" id="palindrome">
<div class="input-container">
<input id="text_input" type="text">
<button id="check-btn" type="submit">Check</button>
</div>
<div class="results-container">
<span id="result"><output name="result_text"></output></span>
</div>
</form>
</div>