gpt4 book ai didi

javascript - 如何使用 JavaScript 或 jQuery 让我的 "input a word"脚本正常工作?

转载 作者:太空宇宙 更新时间:2023-11-04 16:19:19 25 4
gpt4 key购买 nike

HTML 代码:

    <form>
Input: <input type="text" name="input" id="input"><br>
<br>
Output: <input type="text" name="output" id="output"><br>
<input type="submit" value="submit" onclick="yourGuess()" id="submit">
</form>


<div id="answer"></div>

脚本

我不知道如何获取代码来将输入与数组中的单词进行比较,并得出正确或错误的答案并将其放入 div (id=answer) 中。

function yourGuess()
{
var n = 0;
var words = ['banana', 'orange', 'apple', 'peach'];
var guess1 = document.getElementById("input").value;

//wrong answer
if (guess1 !== words) {
document.getElementById("answer").innerHTML = "Wrong!";

}
else {
//right answer
if (guess1 == words) {
document.getElementById("answer").innerHTML = "Correct!";

}
</body>

最佳答案

我建议使用jQuery.inArray()如果你使用 jQuery:

$('#submit').on('click', function(event) {
event.preventDefault();
var wordsArray = ['banana', 'orange', 'apple', 'peach'];
var guessInput = $('#input').val();

/* Check in Array */
if($.inArray(guessInput, wordsArray) !== -1) {
$('#answer').text('Correct!');
} else {
$('#answer').text('Wrong!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Input:
<input type="text" name="input" id="input">
<br>
<input type="submit" value="submit" id="submit">
</form>
<div id="answer"></div>

或者你可以使用 JavaScript 数组 indexOf()方法

function yourGuess() {
var wordsArray = ['banana', 'orange', 'apple', 'peach'];
var guessInput = document.getElementById('input').value;

/* Check indexOf() */
if(wordsArray.indexOf(guessInput) !== -1) {
document.getElementById('answer').innerHTML = 'Correct!';
} else {
document.getElementById('answer').innerHTML = 'Wrong!';
}
}
<form>
Input:
<input type="text" name="input" id="input">
<br>
<input type="submit" value="submit" id="submit" onclick="yourGuess()">
</form>
<div id="answer"></div>

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), to check for the presence of value within array, you need to check if it's not equal to (or greater than) -1.

关于javascript - 如何使用 JavaScript 或 jQuery 让我的 "input a word"脚本正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com