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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11171098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:16:08  来源:igfitidea点击:

object HTMLSelectElement accessing value through this keyword

javascript

提问by Abel Jojo

The below code doesn't it print the value.

下面的代码不打印值。

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

this is the html code

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

回答by T.J. Crowder

selectedIndexis a number, it doesn't have a valueproperty.

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

If you have a selectelement which just allows single-select (as yours does), the easiest way to get its value is the selectelement's valueproperty:

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

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

Double-check that it works on the browsers you want to support, but MaryAnne (see the comments) has checked on all current major browsers and I've checked IE6, IE7, and Firefox 3.6 (e.g., older browsers), and they all work. Since it's specified in DOM2 HTML (the link above)...

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

But re selectedIndex, you probably meant:

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

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

I'd probably take it a bit further and be more defensive:

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

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

...or

...或者

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

...in case there is no selected option (in which case, optionwill be undefined), although with your particularmarkup and code, I'm not aware of a user agent where the changeevent would be fired without there being anything selected. At least, I don't think so — "I think" being the reason for being defensive. :-)

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