我写了一个维基百科搜索网络应用程序,我遇到了一些困难。我没有问题从维基百科api请求数据并在id =“results”的div中以有序的方式显示它们。我遇到的问题是在运行新搜索时清除该元素中的结果。代码如下:
<style>
@import: url('https://fonts.googleapis.com/css?family=Montserrat');
</style>
<body class="container-fluid">
<div class="container-fluid">
<header class="container-fluid text-center">
<h1 style="font-family: 'Monsterrat';">Deep Thought's Databank of Ultimate Knowledge</h1>
</header>
</div>
<div class="container-fluid box">
<div class="container pull-lg-left">
<div class="container-fluid text-center"><h2 style="font-family:'Monsterrat';">Please Enter Your Query/Keyword Below</h2></div>
<input class="form-control" type="text" name="search" id="search" placeholder="Search..."/>
</div>
<div class="container pull-lg-right">
<button class="btn btn-info" id="submit">Submit</button>
<button class="btn btn-primary" id="random" onclick="Random()"><a href="https://en.wikipedia.org/wiki/Special:Random" target="blank" id="randomLink">Random Article</a></button>
</div>
</div>
<div class="container-fluid spacer">
</div>
<div class="container-fluid box">
<span class="text-center" id="results">
</span>
</div>
</body>
脚本代码是:
$(document).ready(function(){
$("#submit").click(function(){
var searchInput = $("#search").val();
var apiUrl = 'https://en.wikipedia.org/w/api.php?action=opensearch&search='+searchInput+'&callback=?';
$.ajax({
type: "GET",
url: apiUrl,
dataType: "json",
async: false,
success: function(data){
for (var n = 0; n <= data.length; n++){
$("#results").append('<a href='+data[3][n]+' target="blank"><br><h1>'+data[1][n]+'</h1></a><br><h3>'+data[2][n]+'</h3><br>');
//console.log(data[1][n]);
}
//console.log(data[3][n]);
},
error: function(err){
alert('Critical Error'+err);
},
})
});
$("#search").bind('keypress', function(e){
if(e.keyCode == 13){
$('#submit').click();
}
})
});
任何帮助将不胜感激。谢谢你们。
- BlackBat023
答案 0 :(得分:0)
您可以使用empty()
与append
内联,以便在添加新结果之前始终清除结果:
var rslt = "";
for (var n = 0; n <= data.length; n++){
rslt += '<a href='+data[3][n]+' target="blank"><br><h1>'+data[1][n]+'</h1></a><br><h3>'+data[2][n]+'</h3><br>';
//console.log(data[1][n]);
}
$("#results").empty().append(rslt);
以下是此方法组合的演示小提琴:https://jsfiddle.net/gn3tq4oc/