英雄职业选择二级联动
效果:
当选择职业时会有与职业对应的英雄选择
样式:
<form action="">
职业:<select id="profession" name="profession"></select>
英雄:<select id="hero" name="hero"></select>
</form>
JS数据:
var professions = ["请选择职业","上单","打野","法师","adc","辅助"];
var heros = [["请选择英雄"],
["狗头","鳄鱼","猴子","老司机","海兽祭祀"],
["瞎子","皇子","酒桶","猪妹","男枪","剑圣"],
["妖姬","小鱼人","火男","小法","发条","安妮"],
["ez","寒冰","卡沙","韦恩","老鼠","小炮"],
["布隆","猫咪","奶妈","堕落天使","锤石","小炮"],
];
JS:
//获取元素
var profession = document.getElementById('profession')
var hero = document.getElementById('hero')
var index = 0
//for(var 变量 in 对象)
for (var i in professions) {
//创建职业的option标签
var option = document.createElement('option')
//innerText返回的是option标签内的文本值并赋值
option.innerText = professions[i]
console.log(option)
//给option.value赋值
option.value = professions[i]
console.log(option)
profession.appendChild(option)
}
//创建英雄的option标签
var c_option = document.createElement('option')
//index 属性可返回下拉列表中选项的索引位置
c_option.innerText = heros[index]
c_option.value = heros[index]
hero.appendChild(c_option)
// console.log(city.options)
profession.onchange = function () {
hero.options.length = 0
//selectedindex 可以获取当前被选中的option的索引
// console.log(this.selectedIndex)
for (var i in heros[this.selectedIndex]) {
var option = document.createElement('option')
option.innerText = heros[this.selectedIndex][i]
option.value = heros[this.selectedIndex][i]
hero.appendChild(option)
}
}