如何实现包含1990至2022赛季选项的下拉菜单?
实现覆盖1990-2022赛季的下拉菜单
原生HTML静态实现
如果不需要动态生成,直接手动编写下拉菜单即可,赛季范围从1990/1991到2021/2022(覆盖1990至2022年的赛季周期):
<select id="season-select"> <option value="1990/1991">1990/1991</option> <option value="1991/1992">1991/1992</option> <!-- 中间年份可按相同规律依次补充 --> <option value="2021/2022">2021/2022</option> </select>
JavaScript动态生成
如果需要自动生成所有赛季选项,避免手动重复编写,用JS循环生成更高效:
const select = document.getElementById('season-select'); // 赛季起始年份从1990到2021(对应赛季为1990/1991至2021/2022) for (let year = 1990; year <= 2021; year++) { const season = `${year}/${year + 1}`; const option = document.createElement('option'); option.value = season; option.textContent = season; select.appendChild(option); }
对应的HTML只需一个空的select容器:
<select id="season-select"></select>
Vue 示例
如果用Vue框架,可以通过计算属性生成赛季列表,再用v-for渲染:
<template> <select v-model="selectedSeason"> <option v-for="season in seasonList" :key="season" :value="season"> {{ season }} </option> </select> </template> <script> export default { data() { return { selectedSeason: '' }; }, computed: { seasonList() { const list = []; for (let year = 1990; year <= 2021; year++) { list.push(`${year}/${year + 1}`); } return list; } } }; </script>
React 示例
在React中,可以通过数组映射生成选项:
import { useState } from 'react'; function SeasonSelect() { const [selectedSeason, setSelectedSeason] = useState(''); // 生成赛季列表 const seasonList = []; for (let year = 1990; year <= 2021; year++) { seasonList.push(`${year}/${year + 1}`); } return ( <select value={selectedSeason} onChange={(e) => setSelectedSeason(e.target.value)} > {seasonList.map(season => ( <option key={season} value={season}> {season} </option> ))} </select> ); } export default SeasonSelect;
内容的提问来源于stack exchange,提问作者Alvin
相关产品推荐
相关产品推荐

