如果你有多个输入框,并希望进行联合精准搜索,可以通过组合多个输入框的值来过滤数据。在JavaScript中,常见的做法是先收集每个输入框的值,然后使用这些值过滤数据。
示例:多个输入框联合精准搜索
假设有多个输入框用于过滤不同的属性(例如姓名、年龄和城市),你可以使用下面的代码来实现联合精准搜索:
html
<input type="text" id="nameSearch" placeholder="Search by name">
<input type="number" id="ageSearch" placeholder="Search by age">
<input type="text" id="citySearch" placeholder="Search by city">
<button onclick="searchData()">Search</button>
<ul id="results"></ul>
<script>
const data = [
{ id: 1, name: 'John', age: 30, city: 'New York' },
{ id: 2, name: 'Jane', age: 25, city: 'Los Angeles' },
{ id: 3, name: 'Mike', age: 35, city: 'Chicago' },
{ id: 4, name: 'Sara', age: 28, city: 'San Francisco' },
];
function searchData() {
const nameTerm = document.getElementById('nameSearch').value.toLowerCase();
const ageTerm = document.getElementById('ageSearch').value;
const cityTerm = document.getElementById('citySearch').value.toLowerCase();
// 联合过滤
const filteredData = data.filter(item => {
return (!nameTerm || item.name.toLowerCase().includes(nameTerm)) &&
(!ageTerm || item.age == ageTerm) &&
(!cityTerm || item.city.toLowerCase().includes(cityTerm));
});
displayResults(filteredData);
}
function displayResults(results) {
const resultsContainer = document.getElementById('results');
resultsContainer.innerHTML = '';
results.forEach(item => {
const li = document.createElement('li');
li.textContent = `${item.name}, ${item.age}, ${item.city}`;
resultsContainer.appendChild(li);
});
}
</script>