给定文本输入,用户可以通过提交点击按钮提交答案or输入键:
</div>
<div class="answer">
<input type="text" placeholder="Enter your answer" class="answer_text" id="answer_text_box">
<input type="button" value="Answer" class="submit_button" id="answer_submit_button">
</div>
我想获得用户输入的文本值,一旦提交他们的答案,可能将其与项目列表list_options进行比较.
这是我的工作;由于我对JS非常陌生,我想到在html文档中编写值以放置持有人标签,然后重新读取html文件并获得值。它似乎并不有效,因为我已经通过.addEventListener获得了值:
<div class="user_answer" id="user_answer_for_js"></div>
这是我在JavaScript中的工作:
const answer_area = document.getElementById('answer_text_box');
const answer_btn = document.getElementById('answer_submit_button');
let list_options = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
// Load all events listerns
loadEventListeners();
// Load all events listerns
function loadEventListeners() {
// Submit answer via submit button:
answer_btn.addEventListener('click', submitButtonClick);
// Submit answer via enter key:
answer_area.addEventListener('keyup', submitEnterKey);
}
function submitButtonClick(e) {
let user_answer = answer_area.value;
document.getElementById("user_answer_for_js").textContent = user_answer.trim();
console.log(`Submit Via Enter Button: ${user_answer}`);
e.preventDefault();
}
function submitEnterKey(e) {
if (e.keyCode === 13) {
let user_answer = answer_area.value;
document.getElementById("user_answer_for_js").textContent = user_answer.trim();
console.log(`Submit Via Enter Key: ${user_answer}`);
e.preventDefault();
}
}
1。获取用户答案必须在加载HTML元素之后加载脚本。现在你的代码正在获取一个尚未加载的html元素。
要做到这一点,在关闭<body>
标签之前放置您的<script>
标签:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</div>
<div class="answer">
<input type="text" placeholder="Enter your answer" class="answer_text" id="answer_text_box">
<input type="button" value="Answer" class="submit_button" id="answer_submit_button">
</div>
<div class="user_answer" id="user_answer_for_js"></div>
<script src="index.js"></script>
</body>
</html>
2。比较使用Array.prototype.includes():
let list_options = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let user_answer = "January";
list_options.includes(user_answer); # False
user_answer = "Monday";
list_options.includes(user_answer); # True
希望有帮助!