繁体   English   中英

在下拉菜单中选择值

[英]Selecting values in a Drop down menu

我是 javascript 的新手,一直在尝试对 4 个不同下拉菜单中的值求和,但是我无法获得选定的值,这是我的代码和 html 的样子: 这是来自chrome的HTML图片

var el = document.getElementsByTagName("select");
var elVal = el.options[el.selectedIndex].value


for(var i=0; i<el.length;i++){
    el[i].onchange = function(){
    var sum = 0;
    sum += parseInt(elVal);
        if(sum!=6){
            alert("blabla");    
        }
    }
}

这是一个示例,说明如何总结四个选择元素的选定选项的值。 该脚本将在每次 select 更改时触发,并在它们的总和不等于 6 时发出警报。它使用HTMLSelectElement.selectedOptions属性来获取当前选择的选项。

 // convert nodeList into array to be able to use reduce() const selects = [...document.getElementsByTagName("select")]; // delegate eventHandling to a common ancestor of our select-elements document.onchange = () => { // sum up the selected options by iterating over the select-elements const sum = selects.reduce((total, select) => { return total + Number(select.selectedOptions[0].value); }, 0); if (sum;== 6) alert('foo'); };
 <select> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <select> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <select> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <select> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM