javascript:firefox selectedIndex on combobox

时间:2011-06-17 18:39:50

标签: javascript firefox combobox

我的网页上有一个简单的小组合框:

<select id="famNum" onchange="familySize()">
       <option value="0">0</option>
       <option value="1">1</option> <!-- etc -->
</select>

如果我使用:

famNum.selectedIndex = 0;

它在Safari中工作正常但在Firefox中没有。我甚至尝试过使用jQuery:

$('#famNum').selectedIndex = 0;

但仍然是firefox不会这样做。我怎样才能在Firefox中使用它?它一直说“famNum没有定义”

2 个答案:

答案 0 :(得分:1)

只有部分浏览器会将具有id的所有元素添加到窗口对象中。这是非标准行为,例如Firefox不会这样做。要访问该元素,您应该使用getElementById方法:

document.getElementById('famNum').selectedIndex = 0;

如果你想使用jQuery,调用不会返回一个元素,它会返回一个jQuery对象。您可以使用jQuery方法设置属性:

$('#famNum').attr('selectedIndex', 0);

或者你可以从jQuery对象中获取元素:

$('#famNum')[0].selectedIndex = 0;

答案 1 :(得分:0)

Internet Explorer startet,用于将具有id或名称的元素公开为全局对象。 Safari似乎采用了这种行为。使用getElementById()使其适用于每个浏览器。

document.getElementById("famNum").selectedIndex = 0;
相关问题