我的代码有一个父选择标签,有两个选项苹果和黄油,每个选项的值为 1 和 2,当我选择苹果时,它将显示另一个选择标签,反之亦然,我的问题是它将显示另一个选择和另一个选择,我需要隐藏另一个选择并显示另一个选择,你能帮助我吗?
代码如下:
$(document).ready(function() {
$('#defList').on('change', function() {
var tarSelect = $(this).val();
console.log(tarSelect);
if (tarSelect == 1) {
var arrayList = [{
val: 1,
text: 'one'
}, {
val: 2,
text: 'two'
}, {
val: 3,
text: 'three'
}];
var selectList = $('<select>').appendTo('#selectBox');
$(arrayList).each(function() {
selectList.append($('<option>').attr('value', this.val).text(this.text));
});
} else if (tarSelect == 2) {
var arrayList2 = [{
val: 1,
text: 'one'
}, {
val: 2,
text: 'two'
}, {
val: 3,
text: 'three'
}];
var selectList2 = $('<select>').appendTo('#selectBox').remove();
$(arrayList2).each(function() {
selectList2.append($('<option>').attr('value', this.val).text(this.text));
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="defList">
<option value="1">Apples</option>
<option value="2">Butter</option>
</select>
<div id="selectBox">
</div>
最佳答案
您最初可以使用 $('#selectBox').html("");
清除新的选择区域。
还要更改 var selectList2 = $('<select>').appendTo('#selectBox').remove();
至var selectList2 = $('<select>').appendTo('#selectBox');
$(document).ready(function() {
$('#defList').on('change', function() {
$('#selectBox').html("");
var tarSelect = $(this).val();
console.log(tarSelect);
if (tarSelect == 1) {
var arrayList = [{
val: 1,
text: 'A one'
},
{
val: 2,
text: 'A two'
},
{
val: 3,
text: 'A three'
}
];
var selectList = $('<select>').appendTo('#selectBox');
$(arrayList).each(function() {
selectList.append($('<option>').attr('value', this.val).text(this.text));
});
} else if (tarSelect == 2) {
var arrayList2 = [{
val: 1,
text: 'B one'
},
{
val: 2,
text: 'B two'
},
{
val: 3,
text: 'B three'
}
];
var selectList2 = $('<select>').appendTo('#selectBox');
$(arrayList2).each(function() {
selectList2.append($('<option>').attr('value', this.val).text(this.text));
});
}
});
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>My first HTML document</TITLE>
</HEAD>
<BODY>
<P>Hello world!</p>
<select id="defList">
<option value="1">Apples</option>
<option value="2">Butter</option>
</select>
<div id="selectBox">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/scripts.js"></script>
</BODY>
</HTML>
关于javascript - 如何使用选择标签隐藏/显示选择标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42051479/