简体   繁体   English

如何正确地将 HTML 输入字段中的文本链接到 JavaScript

[英]How do I properly link text from an input field in HTML to JavaScript

Im tryting to make a simple palindrom checker.我正在尝试制作一个简单的回文检查器。

When Im testing in the console it works fine.当我在控制台中测试时,它工作正常。 However when I try to link it with HTML I cannot get it to work.但是,当我尝试将它与 HTML 链接时,我无法让它工作。 I think this is due to an error extracting the text from the input field in the HTML file...我认为这是由于从 HTML 文件的输入字段中提取文本时出错...

Javascript: 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 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>

When I change the compare(str) to output to the console it works fine:当我将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')
    }
}

You have to retrieve the string from the input at the time you're going to test it, so you have to get it in compare .您必须在测试时从输入中检索字符串,因此您必须在compare中获取它。 How you have it now you're getting the input value before you type in anything.你现在是如何拥有它的,你在输入任何东西之前就得到了输入值。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM