【发布时间】:2023-03-05 19:13:01
【问题描述】:
我对编码很陌生,但我在 freecodecamp 上完成了很多工作,并制作了一些我在 mozilla.developer 上学到的简单猜谜游戏。 我正在使用 VisualStudioCode 并练习。 问题:我想在 input="text" 字段中写一个名字,提交它,然后段落标签应该记录输入名字的姓氏。我在我的网页中创建了两个对象作为用户。我已经足够让控制台在参数中记录名称,但是.. 如我所见,函数 findPerson(name) 参数必须由 inputField 使用。 我该怎么做呢?这是我的代码。
<html>
<div class="form">
<label for="inputField"> Enter a users first name, and see their last name. </label>
<input type="text" class="inputField" id="inputField" placeholder="Enter search here">
<input type="submit" class="submitBtn" id="submitBtn" value="Search">
</div>
<p class="searchResult">Last name will be shown here.</p>
</html>
<script>
const people = [
{
firstName: "Arnold",
lastName: "Schwarzenegger",
hobbies: ["Get pumped", "be awesome"],
},
{
firstName: "Clint",
lastName: "Eastwood",
hobbies: ["Make movies", "not being Arnold"],
},
];
const btn = document.querySelector(".submitBtn");
const inputF = document.querySelector(".inputField");
const para = document.querySelector(".searchResult");
function findPerson(name) {
let word = String(inputF.value);
word = name;
for(var i = 0; i < people.length; i++) {
if(people[i].firstName == name) {
para.textContent = people[i].lastName;
return people[i].lastName;
}
else {
para.textContent = "Not found";
}
}
};
btn.addEventListener("click", findPerson);
</script>
【问题讨论】:
标签: javascript object search