2 回答
TA贡献1829条经验 获得超7个赞
据我了解您的问题,您正在尝试创建一个<ul>标签,该标签具有许多子<li>标签,每个标签都包含过滤后的数据title和author键。
好吧,通常我建议使用 vue.js 之类的东西来管理 UI 的数据绑定,但是由于您提到您希望使用 jQuery 或 vanilla JS 完成此操作,因此它比您想象的要简单。
这是一个完整的 HTML 代码示例,使用 jQuery:
<html>
<body>
<!-- Posts List Container -->
<div>
<ul id="postsContainer"></ul>
</div>
<!-- Post Template (Just an example use-case) -->
<template id="postTemplate">
<li class="post-meta-data">
<h2 class="post-title"></h2>
<strong class="post-author"></strong>
<em class="post-tags"></em>
</li>
</template>
<!-- Include jQuery -->
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
<!-- Our JS Logic -->
<script>
$(function () {
const
$container = $('#postsContainer'),
// Grabs the HTML content of the "tag" template
template = $('#postTemplate').html(),
// Here you can fetch/return your API's or filtered data
// NOTE: I modified the data to showcase the example.
getData = () => {
return [
{
title: "title of post #1",
author: "some guy",
tags: ['foo', 'bar', 'baz'],
},
{
title: "title of post #2",
author: "some other guy",
tags: ['watermelon', 'apple', 'banana'],
}
];
},
// Here you can call this function to update the UI
// based on the data returned by "getData()"
updateSearchTags = () => {
const postsArray = getData();
// Before adding any new elements to the container, we should empty it first.
$container.empty();
for (const post of postsArray) {
const
{ title, author, tags } = post,
$postEl = $(template);
// Hydrate the template with post data
$postEl.find('.post-title').text(title);
$postEl.find('.post-author').text(author);
$postEl.find('.post-tags').text(tags.join(', '));
// Add the post element to the list
$postEl.appendTo($container);
}
};
// Call the UI Update Function whenever necessary
updateSearchTags();
});
</script>
</body>
</html>
TA贡献1796条经验 获得超4个赞
不太确定“返回页面”是什么意思,但您可以map覆盖数据并将其设置为ulwithinnerHTML
function printData(ele, data) {
ele.innerHTML = data.map(item => `<li>${item.title} - ${item.author}</li>`).join('')
}
const ulEle = document.querySelector('#target')
const data = [
{ title: "title of post", author: "some guy" },
{ title: "title of post", author: "some guy" }
]
printData(ulEle, data)
<ul id="target"></ul>
添加回答
举报