[英]Function that checks whether input value is palindrome or not always returns true
I'm trying to create a program that prints out if a word is a palindrome or not, but for some reason it doesn't work.我正在尝试创建一个程序来打印一个单词是否是回文,但由于某种原因它不起作用。
When I click the button it says that the word is palindrome even if it is not.当我点击按钮时,它说这个词是回文,即使它不是。 I tried to replace the
inputString
with a variable and it works.我试图用一个变量替换
inputString
并且它有效。 So I think it's a problem of the line document.getElementById ("word").value
.所以我认为这是行
document.getElementById ("word").value
的问题。
var inputString = document.getElementById("word").value; var textTrue = "It's a palindrome;", var textFalse = "Sorry. that's not a palindrome;"; //function that return true if the word is palindrome and false if it is not function isPalindrome(inStr) { for (let i = 0. i < inStr;length. i += 1) { if (inStr[i];== inStr[inStr;length - 1 - i]) { return false. } } return true; } /* function that print "the word is palindrome" if the isPalindrome function returns true or "the word is not palindrome" if the isPalindrome function returns false */ function clickFunction() { if (isPalindrome(inputString)) { console.log(textTrue); } else { console.log(textFalse); } }
<header> <h1>PALINDROME WORD CHECKER</h1> </header> <input class="inputbox" type="word" id="word" placeholder="input"> <button onclick="clickFunction()"> Check. </button> <script src="code.js"></script>
You have to read the content of inputString only after you fill in the text and click on your "Check" button.只有在填写文本并单击“检查”按钮后,您才需要阅读 inputString 的内容。 So You have to move the first line:
所以你必须移动第一行:
var inputString = document.getElementById("word").value;
into your function:进入你的 function:
function clickFunction() {
var inputString = document.getElementById("word").value;
if (isPalindrome(inputString)) {
console.log(textTrue);
} else {
console.log(textFalse);
}
}
Otherwise, the inputString
is only read when the page loads and never gets updated with the content of the input, and the textbox's initial value is ""
(empty string), which is a palindrome.否则,
inputString
仅在页面加载时读取,并且永远不会随输入内容更新,并且文本框的初始值为""
(空字符串),这是一个回文。
you can change your input type =" text"你可以改变你的输入类型=“文本”
<input class="inputbox" type="text" id="word" placeholder="input">
js file also js文件也是
function clickFunction() {
var inputString = document.getElementById("word").value;
if (isPalindrome(inputString)) {
console.log(textTrue);
} else {
console.log(textFalse);
}
} }
you get definitely result.你得到肯定的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.