昨天做项需求,是动态改变select内部的option。最后做完发现根本不用这个玩意。于是尴尬了,毕竟学习了,所以还是记录下
弄个简单的例子,现在有两个选择器,a,b b的子项要根据a的内容来确定,于是就有了下面的代码:
<select id="select1" class="mui-btn mui-btn-block">
<option value="1">棉</option>
<option value="2">化纤</option>
<option value="3">皮毛</option>
<option value="4">混纺</option>
<option value="5">麻</option>
<option value="6">新型纤维</option>
<option value="7">丝</option>
</select>
<select id="select2" class="mui-btn mui-btn-block" style="margin-right: 10%;margin-top: -33px;">
<option value="item-1">全棉布</option>
<option value="item-2">净色棉</option>
<option value="item-3">灯芯绒</option>
<option value="item-4">帆布</option>
</select>
第一步,先要用id来建立关系:
document.getElementById("select1").onchange = function() {
console.log(document.getElementById("select1").value);
select1value = document.getElementById("select1").value;
selecta = document.getElementById("select1");
selectb = document.getElementById("select2");
第二步,用switch case来搞事情、:
switch(select1value) {
case '1':
console.log("到底什么鬼");
selectb.options.length = 0;
var a11 = document.createElement("option");
a11.text = '全棉布';
a11.value = '全棉布';
selectb.add(a11);
var a11 = document.createElement("option");
a11.text = '净色棉';
a11.value = '净色棉';
selectb.add(a11);
var a11 = document.createElement("option");
a11.text = '灯芯绒';
a11.value = '灯芯绒';
selectb.add(a11);
var a11 = document.createElement("option");
a11.text = '帆布';
a11.value = '帆布';
selectb.add(a11);
var a11 = document.createElement("option");
a11.text = '缎纹/贡缎';
a11.value = '缎纹/贡缎';
selectb.add(a11);
var a11 = document.createElement("option");
a11.text = '棉竹节';
a11.value = '棉竹节';
selectb.add(a11);
var a11 = document.createElement("option");
a11.text = '纱卡';
a11.value = '纱卡';
selectb.add(a11);
var a11 = document.createElement("option");
a11.text = '平布';
a11.value = '平布';
selectb.add(a11);
var a11 = document.createElement("option");
a11.text = '府绸';
a11.value = '府绸';
selectb.add(a11);
var a11 = document.createElement("option");
a11.text = '斜纹';
a11.value = '斜纹';
selectb.add(a11);
var a11 = document.createElement("option");
a11.text = '其他棉类';
a11.value = '其他棉类';
selectb.add(a11);
break;
只上一个就够了,解释一下:
首先。当change事件触发的时候,如果子项里里是1,那么触发该事件,此时:
selectb.options.length = 0;
清空内部所有项
a11.text = '其他棉类';
a11.value = '其他棉类';
var a11 = document.createElement("option");
新建一个子项
设置子项的信息内容
selectb.add(a11);
添加子项到选择器里面去
这两个方法比较常用,就先介绍着两个