对象HTMLSelectElement通过此关键字访问值

Abe*_*ojo 2 javascript

以下代码不会打印该值.

function go(x)
{
   alert(x.options.selectedIndex.value);
   //location=document.menu.student.options[document.menu.student.selectedIndex].value
}
Run Code Online (Sandbox Code Playgroud)

这是html代码

<select name="student" onChange="go(this)">
    <option selected> Student </option>
    <option value="http://www.cnet.com">Attendence</option>
    <option value="http://www.abc.com">Exams</option>
</select>
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 5

selectedIndex是一个数字,它没有value属性.

如果你有一个select只允许单选的元素(就像你的那样),获取其值的最简单方法是select元素的value属性:

function go(x) {
    alert(x.value);
}
Run Code Online (Sandbox Code Playgroud)

仔细检查它是否适用于您想要支持的浏览器,但MaryAnne(请参阅注释)检查了所有当前主流浏览器,并检查了IE6,IE7和Firefox 3.6(例如,旧浏览器),它们都是工作.因为它是在DOM2 HTML(上面的链接)中指定的...

但是selectedIndex,你可能意味着:

function go(x) {
    alert(x.options[x.selectedIndex].value);
}
Run Code Online (Sandbox Code Playgroud)

我可能会更进一步,更加防守:

function go(x) {
    var option = x.options[x.selectedIndex];
    if (option) {
        alert(option.value);
    }
}
Run Code Online (Sandbox Code Playgroud)

...要么

function go(x) {
    var option = x.options[x.selectedIndex];
    var value = option && option.value;
    alert(value); // Alerts "undefined" if nothing is selected
}
Run Code Online (Sandbox Code Playgroud)

...如果没有选择的选项(在这种情况下,option将是undefined),虽然使用您的特定标记和代码,但我不知道change在没有选择任何内容的情况下将触发事件的用户代理.至少,我不这么认为 - "我认为"是防守的原因.:-)