【发布时间】:2020-10-03 20:39:08
【问题描述】:
您好,我已经将所有代码放入链接中,但我不知道如何为名称添加过滤器:https://codepen.io/nutkin/pen/yLOmzom 该表是使用 javascript 中的循环从 json 对象创建的,我可以搜索很多关于如何在 jquery 或 reactjs 中修复它的答案,但我真的很想知道如何在 javascript 中摆弄这个。 让我举个例子:如果用户输入'F'或'f',屏幕应该过滤所有带有'f'和'F'的名字,谢谢大家。下面是代码:
var myContacts = [
{category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"},
{category: "Sporting Goods", price: "$9.99", stocked: true, name: "Baseball"},
{category: "Sporting Goods", price: "$29.99", stocked: false, name: "Basketball"},
{category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"},
{category: "Electronics", price: "$399.99", stocked: false, name: "iPhone 5"},
{category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7"}
];
function generateTable(){
var table=document.createElement('table');
table.style.width='50%';
table.setAttribute('cellspacing','0');
table.setAttribute('cellpading','5');
var col=[];
for(var i=0;i<myContacts.length;i++){
for(var key in myContacts[i]){
if(col.indexOf(key)===-1){
col.push(key);
}
}
}
var tHead=document.createElement('thead');
var hRow=document.createElement('tr');
for(var i=col.length-3;i<col.length;i++)
{
if(col[i]!='stocked')
{
var th=document.createElement('th');
th.innerHTML=col[i];
hRow.appendChild(th);
}
}
tHead.appendChild(hRow);
table.appendChild(tHead);
var tBody=document.createElement('tbody');
for(var i=0;i<myContacts.length;i++)
{
var bRow=document.createElement('tr');
var y=document.createElement('td');
var t=document.createTextNode(myContacts[i].name);
y.appendChild(t);
var z=document.createElement('tr');
var s=document.createTextNode(myContacts[i].price);
z.appendChild(s);
bRow.appendChild(y);
bRow.appendChild(z);
tBody.appendChild(bRow);
if(myContacts[i].stocked===false)
{
y.style.color='red';
}
}
table.appendChild(tBody);
var divContainer=document.getElementById('tableroom');
divContainer.innerHTML='';
divContainer.appendChild(table);
}
<body onload="generateTable()">
<input type="text" name="search" id="searchBar" placeholder="Search..">
<div id='chechbox'>
<input type="checkbox" id='searchBox'>Only show products in stock
</div>
<div id="tableroom" ></div>
</body>
【问题讨论】:
标签: javascript json filter