2 回答
TA贡献1786条经验 获得超13个赞
在该行中,if (input === person1.id) { .. } 您尝试将输入元素与 id 进行比较,而不是与输入的值进行比较。因此
改变
input === person1.id
到
input.value === person1.id
function person(name, age, dob, gender, id) {
this.name = name;
this.age = age;
this.dob = new Date(dob);
this.gender = gender;
this.id = id;
}
// Declaring Variables.
let person1 = new person('John Doe', 19, '2001-02-19', 'male', '001');
let person2 = new person('Jane Doe', 19, '2001-02-22', 'female', '002');
let input = document.getElementById('text');
let show = document.getElementById('result');
let button = document.getElementById('button');
// creating function to run code
button.onclick = function() {
if (input.value === person1.id) {
show.innerHTML = `Name : ${person1.name} <br> Age : ${person1.age} <br> DOB : ${person1.dob} <br> Gender : ${person1.gender}`;
} else if (input === person2.id) {
show.innerHTML = `Name : ${person2.name} <br> Age : ${person2.age} <br> DOB : ${person2.dob} <br> Gender : ${person2.gender}`;
} else {
show.innerHTML = 'Software Crashed!';
console.log(input.value);
console.log(person1.id);
}
}
body {
padding: 0px;
margin: 0;
}
#clear {
padding-top: 50px;
}
#input {
padding: 10px;
margin: auto;
border: 2px solid black;
width: 60%;
}
#text {
padding: 5px;
width: 70%;
}
#button {
padding: 7px;
border: none;
color: white;
background: black;
}
#result {
background: #f1f1f1;
padding: 12px;
width: 60%;
margin: auto;
font-size: 22px;
}
<div id="clear">
</div>
<div id="input">
<input type="text" placeholder="Enter Name For Details" id="text" required>
<button id="button">Submit</button>
</div>
<br>
<br>
<div id="result">
</div>
为了获得正确的日期,正如您在评论中提到的那样,您可以更改格式,
'DD-MM-YYYY'
19-02-2001
到
'YYYY-MM-DD'
2001-02-19
TA贡献1830条经验 获得超3个赞
您需要使用对象检查输入值(而不是输入本身)。因此,将您的button.onclick函数更改为这将解决您的问题:
button.onclick = function() {
if (input.value === person1.id) {
show.innerHTML = `Name : ${person1.name} <br> Age : ${person1.age} <br> DOB : ${person1.dob} <br> Gender : ${person1.gender}`;
} else if (input.value === person2.id) {
show.innerHTML = `Name : ${person2.name} <br> Age : ${person2.age} <br> DOB : ${person2.dob} <br> Gender : ${person2.gender}`;
} else {
show.innerHTML = 'Software Crashed!';
console.log(input.value);
console.log(person1.id);
}
}
- 2 回答
- 0 关注
- 82 浏览
添加回答
举报