[英]Is there a way in jQuery to modify .html() so that it adds code rather than overwriting?
I'm doing work to retrieve data from APIs.我正在努力从 API 检索数据。 I'm designing my code to make multiple queries to the API and then adding them to the running list of results in my HTML.
我正在设计我的代码来对 API 进行多次查询,然后将它们添加到我的 HTML 中的结果运行列表中。 Due to the data returned by the API, there isn't a way to get it all in one shot and then slice it up, I need to get it in multiple shots.
由于 API 返回的数据,没有办法一次获取所有内容然后将其切片,我需要多次获取它。
Look at this code:看看这段代码:
function renderResults(results) {
return $('#results-section').html(genResults(results));
}
The function renderResults()
is being called inside my API call函数
renderResults()
在我的 API 调用中被调用
.fetch(URL)
.then([code that is working properly])
.then(call renderResults() here)
I've console logged my API results and tested the API call in Postman so I know it's constructed correctly- just trying to give proper context.我已经控制台记录了我的 API 结果并在 Postman 中测试了 API 调用,所以我知道它的构造正确 - 只是试图提供适当的上下文。
To review, results
is the data from the API, results-section
is how the results container in my HTML is marked, and the function genResults(results)
creates the template HTML with values from results
stuck into it.回顾一下,
results
是来自 API 的数据, results-section
是我的 HTML 中的结果容器的标记方式,函数genResults(results)
创建模板 HTML,其中包含results
值。
When you use .html
it overwrites everything in the section indicated immediately prior.当您使用
.html
它会覆盖之前指示的部分中的所有内容。 I'm looking for a way to add the template HTML generated by genResults(results)
to any HTML already in the container I have ID'd results-section
, not replace what's there.我正在寻找一种方法将
genResults(results)
生成的模板 HTML 添加到容器中已有的任何 HTML 中,我有 ID results-section
,而不是替换那里的内容。 I've tried chaining on .append()
but can't seem to find a way to do so successfully.我试过链接
.append()
但似乎找不到成功的方法。
The obvious solution is to have a for loop create as many results sub-sections as I need, but the problem is that I don't know how many sections I need until I get the results from the API.显而易见的解决方案是让 for 循环根据需要创建尽可能多的结果子部分,但问题是在从 API 获得结果之前,我不知道需要多少部分。
Any ideas?有任何想法吗?
Update:更新:
Answer from Souvik Ghosh worked. Souvik Ghosh 的回答有效。 I was trying to chain
.append()
on to .html()
, I didn't realize it actually replaces it.我试图将
.append()
到.html()
,我没有意识到它实际上取代了它。
$( "#results-section" ).append( "Your data from the last API call" );
You could use jQuery append.您可以使用 jQuery 追加。
$( "#results-section" ).append( "Your data from the last API call" );
Read more: https://api.jquery.com/append/阅读更多: https : //api.jquery.com/append/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.