th,
td {
height: 50px;
width: 200px;
}
<div>
<p>按照价格查询:<input type="text">-<input type="text">
<input type="button" value="搜索">按照商品名称查询:
<input type="text"><input type="button" value="查询">
</p>
</div>
<table style="text-align: center" border="1" cellspacing='0' cellpadding='0'>
<thead>
<th>id</th>
<th>产品名称</th>
<th>价格</th>
</thead>
<tbody></tbody>
</table>
var data = [{
name: '小米',
id: 1,
price: 3999
},
{
name: 'oppo',
id: 2,
price: 999
},
{
name: '荣耀',
id: 3,
price: 1299
},
{
name: '华为',
id: 4,
price: 1999
},
]
var tbody = document.querySelector('tbody')
var ipts = document.querySelectorAll('[type=text]')
var btns = document.querySelectorAll('[type=button]')
init(data)
function init(data) {
tbody.innerHTML = ''
data.forEach((val) => {
var tr = document.createElement('tr')
tr.innerHTML = '<td>' + val.id + '</td><td>' + val.name + '</td><td>' + val.price + '</td>'
tbody.appendChild(tr)
})
}
btns[0].onclick = function () {
var iptval1 = ipts[0].value.trim()
var iptval2 = ipts[1].value.trim()
if (iptval1 == '' && iptval2 == '') {
return init(data)
} else if (iptval1 == '' && iptval2 != '') {
init(data.filter((val) => {
return val.price <= ipts[1].value
}))
} else if (iptval1 != '' && iptval2 == '') {
init(data.filter((val) => {
return val.price >= ipts[0].value
}))
} else {
init(data.filter((val) => {
return val.price >= ipts[0].value && val.price <= ipts[1].value
}))
}
}
btns[1].onclick = function () {
var index = 0
if (ipts[2].value == '') {
return init(data)
}
if (data.some((val, i) => {
index = i
return val.name == ipts[2].value
})) {
init([data[index]])
} else {
init([])
}
}