使用 javascript 预加载 HTML 下拉列表

preload HTML drop down with javascript

本文关键字:HTML 下拉列表 加载 javascript 使用      更新时间:2023-09-26

我想用我从 Servlet 获得的数据预加载一个下拉菜单。这是我的代码目前的样子:

<script>
var method = ${method};
</script>
<script type="text/javascript">
  function PreselectMyItem(value)
  {
    // Get a reference to the drop-down
    var myDropdownList = document.form.select;
    // Loop through all the items
    for (iLoop = 0; iLoop< myDropdownList.options.length; iLoop++)
    {    
      if (myDropdownList.options[iLoop].value == value)
      {
        // Item is found. Set its selected property, and exit the loop
        myDropdownList.options[iLoop].selected = true;
        break;
      }
    }
  }
</script>
<body onload="init(jsonData); PreselectMyItem(method)">
<div>
            <div id="header">
            <form method="post" action="Servlet" id="form" name="form">
            <table border=0 width=100%>
            <tr>
            <td><select name="method" id="select">
                    <option value="AllDocs">AllDocs</option>
                    <option value="TermTerm">TermTerm</option>
                    <option value="DocsDocs">DocsDocs</option>
                </select></td>
            </tr>
                    </table>
             </form>
             </div>
</div></body>

该值似乎已正确传输,但未在下拉菜单中选择。

<script>
var method = TermTerm;
</script>

你的method变量应该是一个字符串:

var method = "${method}";