如果删除else
部分代码,即使if
语句正常也一切正常,它也会执行else
部分。
为什么会发生这种情况,我该如何解决这个问题?
请帮助我,我是JavaScript的新手。
<!DOCTYPE html>
<html>
<head>
<title>Priject 2</title>
</head>
<body>
<label>Name:
<input type="text" id="name">
</label>
<input type="submit" id="fetch">
<br />
<dl>
<dt>Age</dt>
<dd class="age">-</dd>
<dt>Location</dt>
<dd class="location">-</dd>
<dt>job</dt>
<dd class="job ">-</dd>
<script src="jquery-1.11.1.js"></script>
<script></script>
</dl>
<script src="jquery-1.11.1.js"></script>
<script>
var people=[{
name:"alex",
age:20,
location:"canada",
job:"web developer"
},
{
name:"aliana",
age:21,
location:"japan",
job:"teacher"
}
]
for(i=0;i<people.length;i++){
result(people[i])
}
function result(data){
$("#fetch").on("click",function(){
var name=$("#name").val();
if(data.name ===name ){
$(".age").text(" ");
$(".job").text(" ");
$(".location").text(" ");
$(".age").append(data.age);
$(".job").append(data.job);
$(".location").append(data.location);
}
else if(data.name != name) {
$("body").text(" ")
noresult();
}
})
}
function noresult(){
var noresult="<div><p>name is not in database </p></div>";
$("body").append(noresult);
}
</script>
</body>
</html>
答案 0 :(得分:0)
你的代码几乎一切都很糟糕。我重构了它。
在你的代码中,你做到了:
a = [1,2,3,4]
input = 1
循环数组中的每个项目
输入= 1?是=&gt;获取并附加文本
输入= 2? no =&gt;删除文字显示错误
输入= 3? no =&gt;删除文字显示错误
输入= 4? no =&gt;删除文字显示错误
最后我们收到了错误,但提交的名字很好。
每次点击按钮,都会调用“功能”$("#fetch").on("click",function(){
。然后你可以做你想做的事。
注意:使用.html()
替换内容,而不是.text("")
然后.append(x)
。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Priject 2</title>
</head>
<body>
<label>Name:
<input type="text" id="name">
</label>
<input type="submit" id="fetch">
<br />
<div id="result">
<dl>
<dt>Age</dt>
<dd class="age">-</dd>
<dt>Location</dt>
<dd class="location">-</dd>
<dt>Job</dt>
<dd class="job">-</dd>
</dl>
</div>
<div id="noResult">
<p>name is not in database </p>
</div>
<script>
var people=[{
name:"alex",
age:20,
location:"canada",
job:"web developer"
},
{
name:"aliana",
age:21,
location:"japan",
job:"teacher"
}
]
$("#noResult").hide();
$("#fetch").on("click",function(){
var name=$("#name").val();
// loop through each person in the array and "filter" only matching name into a new array.
var foundPeople = people.filter(function(person){
return name === person.name;
});
// name found => length = 1, not found => length = 0
if(foundPeople.length !== 0){
result(foundPeople[0])
} else {
noresult()
}
})
function result(people){
$(".age").text(people.age);
$(".job").text(people.job);
$(".location").text(people.location);
$("#result").show();
$("#noResult").hide();
}
function noresult(){
$("#result").hide();
$("#noResult").show();
}
</script>
</body>
</html>