我需要一段前端实现筛选的代码
时间: 2023-08-31 09:41:51 浏览: 70
### 回答1:
非常好! 我可以为您提供一个基于 JavaScript 的前端筛选代码示例。
首先,我们需要获取到要进行筛选的数据。假设我们有一个存储了若干个电影的数组:
```
const movies = [
{ title: 'The Shawshank Redemption', year: 1994 },
{ title: 'The Godfather', year: 1972 },
{ title: 'The Godfather: Part II', year: 1974 },
{ title: 'The Dark Knight', year: 2008 },
{ title: '12 Angry Men', year: 1957 },
...
];
```
然后,我们可以使用 HTML 表单元素(如 `<select>` 或 `<input>`)来让用户选择筛选条件。假设我们有一个下拉列表,其中包含了几个可供选择的年份:
```
<label for="year-select">选择年份:</label>
<select id="year-select">
<option value="all">所有年份</option>
<option value="1950">1950 年及以前</option>
<option value="1960">1960 年代</option>
<option value="1970">1970 年代</option>
<option value="1980">1980 年代</option>
<option value="1990">1990 年代</option>
<option value="2000">2000 年代</option>
<option value="2010">2010 年代</option>
<option value="2020">2020 年及以后</option>
</select>
```
接下来,我们可以使用 JavaScript 监听下拉列表的变化事件,并在用户选择不同的年份时进行筛选:
```
const yearSelect = document.querySelector('#year-select');
yearSelect.addEventListener('change', () => {
const selectedYear = yearSelect.value;
let filteredMovies;
if (selectedYear === 'all') {
filteredMovies = movies;
} else {
const minYear = selectedYear.split('-')[0];
const maxYear = selectedYear.split('-')[1];
filteredMovies =
### 回答2:
以下是一个简单的前端实现筛选功能的代码示例:
HTML部分:
```html
<input type="text" id="filterInput" placeholder="输入关键字进行筛选">
<ul id="list">
<li>苹果</li>
<li>香蕉</li>
<li>橙子</li>
<li>葡萄</li>
<li>西瓜</li>
</ul>
```
JavaScript部分:
```javascript
const filterInput = document.getElementById('filterInput');
const list = document.getElementById('list');
filterInput.addEventListener('input', function() {
const filterValue = filterInput.value.toLowerCase();
const items = list.getElementsByTagName('li');
for (let i = 0; i < items.length; i++) {
const itemText = items[i].innerText.toLowerCase();
if (itemText.includes(filterValue)) {
items[i].style.display = 'block';
} else {
items[i].style.display = 'none';
}
}
});
```
这段代码实现了一个简单的筛选功能。当输入框输入关键字时,会根据关键字动态显示或隐藏列表中的项目。列表项的显示与隐藏通过设置`display`属性实现。函数`includes()`用于判断字符串是否包含关键字。