繁体   English   中英

有没有更好的方法使用jQuery附加HTML

[英]Is there a better way to append HTML using jQuery

我创建了一个访问Wikipedia API的Wikipedia finder 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

您必须先清除.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>'); } } }); }); }); 
 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; } 
 <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> 

如果您真的想要JQuery:

$('.results').html('<a class="linksa" href=' + testCheck[key].fullurl +'> <div class="entryOne"><h1>'+ testCheck[key].title + '</h1>'+testCheck[key].extract+'</p></div></a>');

或仅使用香草javascript:

document.querySelector(".results").innerHTML = '<a class="linksa" href=' + testCheck[key].fullurl +'> <div class="entryOne"><h1>'+ testCheck[key].title + '</h1>'+testCheck[key].extract+'</p></div></a>';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM