繁体   English   中英

获取Internet Explorer中SELECT框的值

[英]Getting the value of a SELECT box in Internet Explorer

我有一个选择框:

<select id="item1" name="Item 1">
  <option> </option>
  <option> Camera </option>
  <option> Microphone </option>
  <option> Tripod </option>
</select>

我有这个JavaScript:

var item1= document.getElementById("item1").value;

item1始终显示为空,从不选择选项。 但是,这适用于

使用item.value适用于除非常旧的浏览器之外的所有浏览器(Netscape 4任何人?)。 它在这种情况下不起作用的原因是因为选项中没有值属性。 您应该为每个属性声明值。 您当前拥有的只是“text”属性,通常在没有声明值时默认为value。 或者,您可以在窗口onload事件中推送一些代码,使每个选项的“值”与“text”相同。

第三种方法,你可以使用下面的代码,这是老式的方式:

var s = document.getElementById('item1');
var item1 = s.options[s.selectedIndex].value;

由于您的选项标签没有属性“value”,因此IE6和IE7会返回一个空字符串。 您应该从Option对象的“text”字段中读取值,如下所示:

var item1 = s.options[s.selectedIndex].text;

在item1中,您将拥有所需的价值而不会破坏与Firefox和IE 8的兼容性。

作为回答#1的附录,要小心,因为<select> .selectedIndex可能会为-1,这会在传入<select> .options [n]时引发异常。 因此,您可能希望进行快速测试:

var s = document.getElementById('item1');
var item = (-1 != s.selectedIndex)? 
               s.options[s.selectedIndex] : null;

编辑

根据Tim的评论,如果你通过JavaScript设置它或者你创建一个空的<select>框,s.selectedIndex可以是-1。

用于从SELECT框中获取名为layerDetails.styleColumn (SELECT标记具有相同名称和Id)的可变columnName的代码,适用于所有浏览器...

var columnName = document.getElementsByName('layerDetails.styleColumn')[0].value;
if ( columnName == null || columnName == '' )
  {
  columnName = document.getElementById('layerDetails.styleColumn').value;
  }

if ( columnName == null || columnName == '' )
  {
  var select = document.getElementById('layerDetails.styleColumn');
  columnName= select.options[select.selectedIndex].value;
  if ( columnName == null || columnName == '' )
    {
    columnName= select.options[select.selectedIndex].text;
    }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM