Javascript onchange 事件。选择/选项 html 下拉输入

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

Javascript onchange event. select/option html dropdown input

javascriptformsaddeventlistener

提问by DVCITIS

var inputDrop = document.createElement('select');
inputDrop.setAttribute("onchange", function test(){alert("test");});
form.appendChild(inputDrop);


var inputOpt1 = document.createElement('option');
inputOpt1.value="1";
inputOpt1.innerHTML="1";
inputDrop.appendChild(inputOpt1);

var inputOpt2 = document.createElement('option');
inputOpt2.value="2";
inputOpt2.innerHTML="2";
inputDrop.appendChild(inputOpt2);

form.appendChild(inputDrop);

I need to assign somekind of event handler to selectdropdown input field with a number of options. I need to execute a function whenever a different option is selected. The above doesnt work and neither does inputDrop.onchange="alert('test')";not sure what im doing wrong here, please could someoneadvise?

我需要分配某种事件处理程序来选择具有多个选项的下拉输入字段。只要选择了不同的选项,我需要执行函数。以上不起作用,inputDrop.onchange="alert('test')"; 不确定我在这里做错了什么,请有人建议吗?

thanks.

谢谢。

回答by pjdanfor

Pete. What you're looking for is something like

皮特。你正在寻找的是类似的东西

inputDrop.addEventListener('change', function() {
    alert("PETE'S TEST"); });

I put together a jsFiddle to demonstrate this working: http://jsfiddle.net/pbaXP/1/

我整理了一个 jsFiddle 来演示这个工作:http: //jsfiddle.net/pbaXP/1/

回答by Arun P Johny

This seems to be working

这似乎有效

inputDrop.onchange = function test(){alert("test");};

Working demo here

工作演示在这里