我有一个json文件,我使用javascript将其转换为html表。我希望能够对json文件的数组进行排序,以便仅在单击按钮时才显示特定项目。
我已经在线阅读了有关javascript中的onclick()函数的信息,但我不知道如何将其集成到仅在html表中显示json文件某些项的函数中。
var petsData = [{
name: "Purrsloud",
species: "Cat",
favFoods: ["wet food", "dry food", "<strong>any</strong> food"],
birthYear: 2016,
photo: "https://learnwebcode.github.io/json-example/images/cat-2.jpg"
},
{
name: "Barksalot",
species: "Dog",
birthYear: 2008,
photo: "https://learnwebcode.github.io/json-example/images/dog-1.jpg"
},
{
name: "Meowsalot",
species: "Cat",
favFoods: ["tuna", "catnip", "celery"],
birthYear: 2012,
photo: "https://learnwebcode.github.io/json-example/images/cat-1.jpg"
}
];
var tableStart = `
<table>
<tr>
<th>Name</th>
<th>Species</th>
<th>Birth Year</th>
<th>Favorite Foods</th>
</tr>`;
var tableEnd = `
</table>`;
function foods(foods) {
return `
<h4>Favorite Foods</h4>
<ul class="foods-list">
${foods.map(food => `<li>${food}</li>`).join("")}
</ul>
`;
}
function petTemplate(pet) {
return `
<tr>
<td>${pet.name}</td>
<td>${pet.species }</td>
<td>${pet.birthYear}</td>
<td>${pet.favFoods ? foods(pet.favFoods) : ""}</td>
</tr>
`;
}
document.getElementById("table").innerHTML = `
${tableStart}
${petsData.map(petTemplate).join("")}
${tableEnd}
`;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnCats">cats</button>
<button id="btnDogs">dogs</button>
<div id="table"></div>
这是我用来将json文件制成表格的代码。如何在我的桌子上有一个显示狗的按钮和一个显示猫的按钮?
答案 0 :(得分:1)
添加了此代码
var catButton = document.getElementById("btnCats");
var dogButton=document.getElementById("btnDogs");
catButton.addEventListener("click",(event)=>{
let catsData=petsData=petsData.filter(value=>
value.species=="Cat");
document.getElementById("table").innerHTML = `
${tableStart}
${catsData.map(petTemplate).join("")}
${tableEnd}
`;
});
dogButton.addEventListener("click",(event)=>{
let dogsData=petsData.filter(value=>
value.species=="Dog");
document.getElementById("table").innerHTML = `
${tableStart}
${dogsData.map(petTemplate).join("")}
${tableEnd}
`;
});
最好创建一个函数并将其用于上面的代码
像这样的东西
function drawTable(){
document.getElementById("table").innerHTML = `
${tableStart}
${petsData.map(petTemplate).join("")}
${tableEnd}
`;
}
所以您可以将其用作
dogButton.addEventListener("click",(event)=>{
petsData=petsData.filter(value=>
value.species=="Dog");
drawTable();
});
答案 1 :(得分:0)
您可以用这种方式写短片
点击我!
如果您要调用任何函数,则说sortedFun,它对值进行排序,比您可以将函数调用为
点击我! 确保sortedFun()是用js编写的,并且已加载js代码。