[英]HTML/Javascript - How to display text from input field as HTML code?
[英]How do I properly link text from an input field in HTML to JavaScript
我正在尝试制作一个简单的回文检查器。
当我在控制台中测试时,它工作正常。 但是,当我尝试将它与 HTML 链接时,我无法让它工作。 我认为这是由于从 HTML 文件的输入字段中提取文本时出错...
Javascript:
const str = document.getElementById('input').value;
function reverseString(str){
let string = str.toLowerCase();
let splitStr = string.split('');
let revString = splitStr.reverse('');
let joinStr = revString.join('');
return joinStr;
}
function compare(str){
if (reverseString(str) === str){
document.querySelector("#answer").innerHTML = 'Its a Palindrom';
} else {
document.querySelector("#answer").innerHTML = 'Its not a Palindrom';
}
}
HTML
<body>
<div class="checkerContainer">
<h1 id="heading">Palendrom Checker</h1>
<h2 id="subtext">Enter a word of phrase!</h2>
<div id="answer">Answer will output here!</div>
<input type="text" id="input" placeholder="Enter your word or phrase here!">
<button type="button" id="submit" onclick="compare(str)">Check!</button>
</div>
</body>
当我将compare(str)
更改为输出到控制台时,它工作正常:
const str = document.getElementById('input').value;
function reverseString(str){
let string = str.toLowerCase();
let splitStr = string.split('');
let revString = splitStr.reverse('');
let joinStr = revString.join('');
return joinStr;
}
function compare(str){
if (reverseString(str) === str){
console.log('Its a Palindrom')
} else {
console.log('Its not a Palindrom')
}
}
您必须在测试时从输入中检索字符串,因此您必须在compare
中获取它。 你现在是如何拥有它的,你在输入任何东西之前就得到了输入值。
function compare(){
const str = document.getElementById('input').value;
if (reverseString(str) === str){
document.querySelector("#answer").innerHTML = 'Its a Palindrom';
} else {
document.querySelector("#answer").innerHTML = 'Its not a Palindrom';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.