2 回答
TA贡献1827条经验 获得超4个赞
这并不完美,但它是如何动态更改<select>元素中的选项的示例。更新了 codepen 示例。
HTML:
<html>
<button id='button' onClick='handleClick()'>Change Array</button>
<input type='number' id='number' value='0' onChange='handleChange()'/>
<select id='select'>
</select>
</html>
JavaScript:
const lists = [
{
one: { value: 1 },
two: { value: 2 },
three: { value: 3}
},
{
four: { value: 4 },
five: { value: 5 },
six: { value: 6}
},
{
seven: { value: 7 },
eight: { value: 8 },
nine: { value: 9 }
}
]
const inputNumber = document.getElementById('number')
const select = document.getElementById('select')
function handleClick() {
inputNumber.value = parseInt(inputNumber.value) + 1
handleChange()
}
function handleChange() {
select.innerHTML = '' // Removes previous list options on update
const currentNumber = parseInt(inputNumber.value)
const currentList = lists[currentNumber - 1]
const keys = Object.keys(currentList)
keys.map((key, index) => {
const newOption = document.createElement('option')
newOption.value = currentList[key].value
newOption.innerHTML = key
select.appendChild(newOption)
})
}
TA贡献2051条经验 获得超10个赞
There are two function one for which option is selected and according
selected value switch call second function named runValues(array) with
parameter as array and set option in second select box.
copy script and html code and paste in your code necessary place and check
and verify.
<script>
var addItems = ['elements to an array', 'elements at the end'];
var test = ['test', 'hhh'];
var arrFindItems = ['milk', 'eggs', 'sugar', 'keys'];
function event_function()
{
var select_one = document.getElementById("select_one");
var selected_option = select_one.options[select_one.selectedIndex];
switch(selected_option.value)
{
case "addItems" :
runValues(addItems);
break;
case "removeItem" :
runValues(test);
break;
case "findItems" :
runValues(arrFindItems);
break;
}
}
function runValues(arr)
{
var secondOption = document.getElementById('second_select');
secondOption.innerHTML = "";
alert("First Element of Array : " + arr[0]);
for (var i = 0; i < arr.length; i++)
{
secondOption.innerHTML += '<option>' + arr[i] + '</option>';
}
}
//Html File
<html>
<body>
I Have An Array :
<select class="arrOptions" id="select_one" onchange="event_function()">
<option value="addItems">Add Items to an Array</option>
<option value="removeItem">Remove Items</option>
<option value="findItems">Find Items</option>
<option value="walkOver">Walk Over Items</option>
<option value="returnString">Return a String</option>
<option value="orderArray">Walk Over Items</option>|
<option value="other">Other</option>
</select>
I m interested in :
<select id="second_select">
</select>
</body>
</html>
添加回答
举报