函数被一个值卡住(它返回,但该值不更新)JS



我有一个JS函数,它执行以下操作:当在输入中键入文本并按下按钮时,该函数会分析字符串,看看它是否有以下任何字母:如果它包含字母"a"b";,或";c";,它返回"0";完美";如果它包含";d"e"f";,返回";"好";,等等

事实证明,当在浏览器中进行测试时,该功能只能工作一次。如果我在运行函数后插入一个新的输入,它会一直返回以前的值。

例如:如果我输入文本";ABC";,它返回"0";完美的";但如果在那之后,我插入文本";DEF";,它保持返回值"0";完美";,而实际上它应该返回"0";很好;。

const textInput = document.getElementById("nameInput").value;
const button = document.getElementById("btn");
const checkLetters = () => {
for (i in textInput) {
if (textInput.match(/a|b|b/gi)) {
document.getElementById("resultOutput").innerHTML = "Perfect.";
return;
} else if (textInput.match(/d|e|f/gi)) {
document.getElementById("resultOutput").innerHTML = "Good.";
return;
} else {
document.getElementById("resultOutput").innerHTML = "Bad";
return;
}
}
};
checkLetters(textInput);
<div class="input">
<input id="nameInput" type="text" onkeyup="keyUp(event);" />
<button id="btn" type="button" aria-label="result" onclick="checkLetters(textInput)" </button>
</div>
<div class="output">
<output id="resultOutput" type="text"></output>
</div>

我想出了一个在桌面上工作的解决方案,但在移动设备上失败了:;window.location.reload((&";在HTML按钮内部,以便该按钮在执行该功能之前刷新浏览器。通过这种方式,函数会返回新鲜的、没有先前值的值,并且工作正常。

<button id="btn" type="button" aria-label="result" onclick="window.location.reload(); checkSyllables(catsName)"</button>

但这个解决方案似乎非常野蛮和丑陋,我想永远解决这个问题,就在JS中,而不是我做的那样(也因为它在移动设备上不起作用(。

我感谢所有的帮助!我的代码可能很糟糕,我可以使用更好的方法,但这是我设法做到的最好的方法,因为我一个月前才开始编程。

您不需要遍历字符串的每个字符来检查它是否与您的RegExp匹配;此外,对于您的用例,test()方法似乎比match()方法更合适。最后,您可以将a|b|cd|e|f替换为等效的范围[a-c][d-f]

如果你把所有的东西放在一起,并添加一些关注点的分离,你最终会得到类似的东西:

const input = document.getElementById('nameInput');
const output = document.getElementById('resultOutput');
const btn = document.getElementById('btn');
btn.addEventListener('click', (event) => checkLetters());
input.addEventListener('keyup', (event) => keyUp(event));
function keyUp(event) {
// ... do stuff
}
function checkLetters() {
const inputTxt = input.value;
if (/[a-c]+/gi.test(inputTxt)) {
output.innerText = 'Perfect.';
} else if (/[d-f]+/gi.test(inputTxt)) {
output.innerText = 'Good.';
} else {
output.innerText = 'Bad.';
}
}
<div class="input">
<input id="nameInput" type="text" />
<button id="btn" type="button" aria-label="result">check</button>
</div>
<div class="output">
<output id="resultOutput" type="text"></output>
</div>

首先,您的脚本缺少结束标记,这是正确的脚本:

const textInput = document.getElementById("nameInput").value;
const button = document.getElementById("btn");
const checkLetters = () => {
for (i in textInput) {
if (textInput.match(/a|b|b/gi)) {
document.getElementById("resultOutput").innerHTML = "Perfect.";
return;
} else if (textInput.match(/d|e/f)) {
document.getElementById("resultOutput").innerHTML = "Good.";
return;
} else {
document.getElementById("resultOutput").innerHTML = "Bad";
return;
}
}
};

最新更新