我正在尝试创建一个从属下拉列表,如果选择了第一个选项,它只会显示div class option1
,如果选择了选项2,它会显示div class option2
,我不擅长JavaScript,(不是jQuery)我正在寻求一些帮助
<select id="lstFruits" >
<option value="1">Mango</option>
<option value="2">Apple</option>
</select>
<div class ="option1">
<br/><br/>
Colour1 <input type="text"/>
<br/>
Taste1 <input type="text"/>
<br/>
weight1 <input type="text"/>
</div>
<div class="option2">
<br/><br/>
Colour2 <input type="text"/>
<br/>
Taste2 <input type="text"/>
<br/>
weight2 <input type="text"/>
</div>
答案 0 :(得分:1)
您可以使用此代码:
// Let the DOM load before addressing elements:
document.addEventListener('DOMContentLoaded', function () {
var fruits = document.querySelector('#lstFruits'),
divs = [document.querySelector('.option1'),
document.querySelector('.option2')];
function showMatchingOptions() {
// Show and hide the correct div, based on the selected value
divs[+this.value-1].style.display = '';
divs[2-this.value].style.display = 'none';
}
// Execute the above function on every change in the select list
fruits.addEventListener('change', showMatchingOptions);
// Execute the above function also on page load, so we
// start with a consistent situation.
showMatchingOptions.call(fruits);
});
&#13;
<select id="lstFruits" >
<option value="1">Mango</option>
<option value="2">Apple</option>
</select>
<div class ="option1">
<br/><br/>
Colour1 <input type="text"/>
<br/>
Taste1 <input type="text"/>
<br/>
weight1 <input type="text"/>
</div>
<div class="option2">
<br/><br/>
Colour2 <input type="text"/>
<br/>
Taste2 <input type="text"/>
<br/>
weight2 <input type="text"/>
</div>
&#13;
如果您有2个以上的元素,则可以使用for
循环:
var fruits = document.querySelector('#lstFruits'),
divs = [document.querySelector('.option1'),
document.querySelector('.option2'),
document.querySelector('.option3')];
function showMatchingOptions() {
// Show and hide the correct div, based on the selected value
for (var i = 0; i < 3; i++) {
divs[i].style.display = +this.value-1 === i ? '' : 'none';
}
}
答案 1 :(得分:0)