我的工作是在一个下拉选择默认值。我能做到这一点,我的问题是,我的函数默认值似乎是空的?顺便说一下,我没有使用属性(selected="selected"),因为选项是动态创建的。我只是在我的例子中添加了一个选项值,以便更好地理解。
HTML: <tr>
<td>Status Found</td>
<td>
<select id="lstExtStatusFound">
<option value=" "> </option>
<option value="ON">On</option>
<option value="OFF">Off</option>
</select>
</td>
</tr>
<tr>
<td>Status Left</td>
<td>
<select id="lstExtStatusLeft">
<option value=" "> </option>
<option value="ON">On</option>
<option value="OFF">Off</option>
</select>
</td>
</tr>
Javascript: function defaultStatus(){
var statusFound = document.getElementById("lstExtStatusFound").selectedIndex = 2;
statusFound.selected = true;
var statusLeft = document.getElementById("lstExtStatusLeft").selectedIndex = 2;
statusLeft.selected = true;
}
这可能不是您的主要问题,但是当您将document.getElementById("lstExtStatusFound").selectedIndex = 2
分配给变量时,该变量将具有值2
。
要存储dom元素,你应该为它创建一个变量,然后对它的属性进行操作
var statusFound = document.getElementById("lstExtStatusFound")
statusFound.selectedIndex = 2;
statusFound.selected = true;
对我来说也很好:https://jsfiddle.net/p3pbguus/1/