2

下面的代码不会打印值。

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

这是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>
4

1 回答 1

5

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

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

function go(x) {
    alert(x.value);
}

仔细检查它是否适用于您想要支持的浏览器,但 MaryAnne(请参阅评论)已经检查了所有当前的主要浏览器,并且我检查了 IE6、IE7 和 Firefox 3.6(例如,较旧的浏览器),它们都工作。由于它是在 DOM2 HTML 中指定的(上面的链接)...

但是 re selectedIndex,您可能的意思是:

function go(x) {
    alert(x.options[x.selectedIndex].value);
}

我可能会更进一步,更具防御性:

function go(x) {
    var option = x.options[x.selectedIndex];
    if (option) {
        alert(option.value);
    }
}

...或者

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

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

于 2012-06-23T16:27:22.477 回答