Javascript函数在循环中不起作用,但如果单独运行则会起作用

时间:2017-02-18 14:30:00

标签: javascript html loops

我想根据相关的变量状态预先选择几个(x30)选项框形式中的选项。

每个选项框都有一个ID:selectbox_1 to selectbox_30

要在每个选项框中预先选择正确的选项,我使用以下效果很好:

setSelectedIndex(document.getElementById('selectbox_1'), getXMLValue(xmlData, 'SCHEDULE_1'));

setSelectedIndex(document.getElementById('selectbox_'), getXMLValue(xmlData, 'SCHEDULE_2'));

...

setSelectedIndex(document.getElementById('selectbox_30'), getXMLValue(xmlData, 'SCHEDULE_30'));

因为在循环中这样做应该更容易和更清楚,我尝试了以下内容,但由于某些未知的原因,它不起作用,请你帮忙吗?

<script type = "text/javascript">
  for (i = 1; i <= 30; i++) {
    setSelectedIndex(document.getElementById('selectbox_' + i), getXMLValue(xmlData, 'SCHEDULE_' + i));
  } 
</script>

function setSelectedIndex(s, valsearch) {
  // Loop through all the items in drop down list
  for (i = 0; i < s.options.length; i++) {
    if (s.options[i].value == valsearch) {
      // Item is found. Set its property and exit
      s.options[i].selected = true;
      break;
    }
  }
  return;
}
<form method="get" action="sensors.htm" id="sensor_1">
  <select name="schedule" id="selectbox_1" value="~maj_sensor_schedule(1)~">
  <option value="0">never</option>
  <option value="1">every 1 minute</option>
	<option value="2">every 5 minutes</option>
	<option value="3">every 10 minutes</option>
	<option value="4">every 15 minutes</option>
	<option value="5">every 30 minutes</option>
	<option value="6">every hour</option>
	<option value="7">every 2 hours</option>
	<option value="8">every 4 hours</option>
	<option value="9">every 8 hours</option>
	<option value="10">every 12 hours</option>
	<option value="11">everyday</option>
	<option value="12">every week</option>
</select>
  <input src="./checked.png" onclick="document.getElementById('sensor_1').submit()" align="center" type="image"></form>



<form method="get" action="sensors.htm">

  <select name="schedule" id="selectbox_2" value="~maj_sensor_schedule(2)~">
			
		<option value="0">never</option>
		<option value="1">every 1 minute</option>
		<option value="2">every 5 minutes</option>
		<option value="3">every 10 minutes</option>
		<option value="4">every 15 minutes</option>
		<option value="5">every 30 minutes</option>
		<option value="6">every hour</option>
		<option value="7">every 2 hours</option>
		<option value="8">every 4 hours</option>
		<option value="9">every 8 hours</option>
		<option value="10">every 12 hours</option>
		<option value="11">everyday</option>
		<option value="12">every week</option>
		</select>
  <input src="./checked.png" onclick="document.getElementById('sensor_2').submit()" align="center" type="image"> </form>

0 个答案:

没有答案