使用纯 JavaScript 获取事件的选择元素值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11683934/
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 14:00:08  来源:igfitidea点击:

Get select element value on event using pure JavaScript

javascriptjavascript-eventsevent-handlinghtml-select

提问by AlexMorley-Finch

I want to get the value of a select element when the select element is clicked! I want to do it without an onchangeattribute in the HTML.

我想在单击选择元素时获取选择元素的值!我想onchange在 HTML 中没有属性的情况下做到这一点。

I would like to achieve this without jQuery. I don't want to include a jQuery framework into this website when this tiny script is the only thing I need.

我想在没有 jQuery 的情况下实现这一点。当这个小脚本是我唯一需要的东西时,我不想在这个网站中包含一个 jQuery 框架。

var select_element = document.getElementById('product-form-user-enquiry-type');

select_element.onchange = function(e){
    if (!e)
        var e = window.event;
    var svalue = select_element.value;
    alert( svalue );
}
if ( select_element.captureEvents ){
    select_element.captureEvents(Event.CHANGE);
}

The select_element.value;contains an empty string. How should I do this?

select_element.value;包含一个空字符串。我该怎么做?

采纳答案by AymKdn

A solution that will work with all browsers (including IE8) :

适用于所有浏览器(包括 IE8)的解决方案:

var select_element = document.getElementById('product-form-user-enquiry-type');

select_element.onchange = function() {
    var elem = (typeof this.selectedIndex === "undefined" ? window.event.srcElement : this);
    var value = elem.value || elem.options[elem.selectedIndex].value;
    alert(value);
}?

回答by Gavin

?document.getElementById('test').onchange = function() {
    alert(this.options[this.selectedIndex].val???ue);
};?

Does the above the work?

以上有效吗?

Edit:

编辑:

Edited to reflect your select id's etc.

编辑以反映您选择的 ID 等。

var select_element = document.getElementById('product-form-user-enquiry-type');

select_element.onchange = function(e){
    if (!e)
        var e = window.event;
    var svalue = this.options[this.selectedIndex].value;
    alert( svalue );
}?

See it working at: http://jsfiddle.net/gRoberts/4WUsG/

看到它的工作:http: //jsfiddle.net/gRoberts/4WUsG/

回答by vladkras

.onchange = function() { ... }seems to overwrite other handlers, so I use addEventListener("change", function() { ... })

.onchange = function() { ... }似乎覆盖其他处理程序,所以我使用addEventListener("change", function() { ... })