当然,这不应该太难吧?
我有一个元素在一个滚动框中显示:
我有一个元素在一个滚动框中显示:
<select id="selectBox" name="select" size="15" style="width:190px;">
<!-- <options> are added via javascript -->
</select>
目前,我正在使用这段 JavaScript 来获取元素,但它没有起作用:
//Calculate all numbers
var x=[];
function calculate()
{
for (var i = 0; i < 999; i++)
{
x[i]=selectbox.options[i].value;
alert(x[i]);
}
}
Calculate()
函数被一个按钮调用。但是出现了一些严重的问题,我无法解决。之前定义的selectbox
已经是var selectbox = document.getElementById("selectBox");
,这个已经可以正常工作。
这里调用alert只是为了尝试调试代码...
我使用数字999
,因为我不知道如何得到<select>
元素中有多少个选项(因为它在滚动框格式中)。
解决方案必须是JavaScript,并且列表框必须采用滚动框格式。
感谢您的帮助!
编辑——好的,下面附上更多的代码以帮助理解。
<form id="aggregateForm">
<input id="inputNum" value="" type="text"><input id="addnum" value="Add" onclick="add();" type="button">
<br>
<select id="selectBox" name="select" size="15" style="width:190px;">
</select>
<br>
<input id="calculate" value="Calculate" onclick="calculate();" type="button"><input id="reset" value="Reset" onclick="reset();" type="button">
</form>
<script type="text/javascript">
var selectbox = document.getElementById("selectBox");
function add()
{
//Function to add a new number to the list of digits
//Parses an integer to ensure everything works okay
if(IsNumeric(document.getElementById("inputNum").value) == true)
{
selectbox.options[selectbox.options.length] = new Option(document.getElementById("inputNum").value, document.getElementById("inputNum").value);
inputNum.focus();
}
else if(IsNumeric(document.getElementById("inputNum").value) == false)
{
alert("I'm sorry, but you have entered an invalid number. Please enter a number into the input box.");
inputNum.focus();
}
}
//Calculate all numbers
var x=[];
function calculate()
{
for (var i = 0; i <selectbox.options.length; i++)
{
x[i]=selectbox.options[i].value;
alert(x[i]);
}
}
//IsNumeric function coding taken from https://dev59.com/3nVD5IYBdhLWcg3wU56H code by Joel Coehoorn
function IsNumeric(input)
{
return (input - 0) == input && input.length > 0;
}
</script>
alert=(x[i]);
- Thiloalert
是错误的? - Singular1tyalert(x[i])
更像是你想要的。或者在循环后面加上console.log(x)
。 - Thilo