我创建了一个访问维基百科API的维基百科查找器Web应用程序。但是,要将JSON数据附加到HTML,我使用了append()
函数:
$('.results').append('<a class="linksa" href=' + testCheck[key].fullurl +'> <div class="entryOne"><h1>'+ testCheck[key].title + '</h1>'+testCheck[key].extract+'</p></div></a>');
问题是当用户想要搜索新词到搜索栏时。由于append()
,新结果属于之前的结果。我的应用程序的codepen是https://codepen.io/mrsalami/pen/NwrGjj
答案 0 :(得分:2)
在添加新内容之前,您必须先清除.result
,并在
$(document).ready(function(){
$(".button").on("click", function(){
var value = $('#searchItem').val();
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=info%7Cextracts&list=&generator=search&utf8=1&inprop=url&exsentences=2&exintro=1&gsrsearch=" + value + "&gsrlimit=10&origin=*"
$.getJSON(url, function(x) {
var testCheck = x.query.pages;
// Clear the div before appending current result
$('.results').html("");
for (var key in testCheck) {
if (testCheck.hasOwnProperty(key)) {
console.log(testCheck[key].title);
console.log(testCheck[key].fullurl);
console.log(testCheck[key].extract);
$('.results').append('<a class="linksa" href=' + testCheck[key].fullurl +'> <div class="entryOne"><h1>'+ testCheck[key].title + '</h1>'+testCheck[key].extract+'</p></div></a>');
}
}
});
});
});
&#13;
header {
text-align: center;
margin-bottom: 40px;
}
.entryOne {
background-color: white;
border: 6px solid red;
min-height: 90px;
padding: 10px;
margin-bottom: 30px;
}
.linksa {
text-decoration: none !important;
color: black;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<h1>Jafar Wikipedia Search</h1>
<input type="text" name="searchItem" class="searchItem" id="searchItem" placeholder="Search">
<a class="button">Button</a>
</header>
<div class="results"></div>
&#13;
答案 1 :(得分:0)
如果你真的想要JQuery:
img[100:400]
或者只使用vanilla javascript:
$('.results').html('<a class="linksa" href=' + testCheck[key].fullurl +'> <div class="entryOne"><h1>'+ testCheck[key].title + '</h1>'+testCheck[key].extract+'</p></div></a>');