javascript 添加一个 onchange 事件来选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15465679/
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
adding an onchange event to select
提问by
I have the following js code:
我有以下js代码:
function createConBox() {
var charDiv = document.getElementById("characterList"); // reference to "characterList" div
header = document.createElement("p"); // creates the <p> tag
charDiv.appendChild(header); // adds the <p> tag to the parent node
title = document.createTextNode("Show Only Lines By:"); // creates the text string
header.appendChild(title); // adds the text string to the parent node
// create select box and add elements
selectBox = document.createElement("select");
selectBox.setAttribute("id", "cList");
charDiv.appendChild(selectBox);
charNames = uniqueElemText("h3"); // array of character names
newOption = document.createElement("option");
selectBox.appendChild(newOption);
newOptionTitle = document.createTextNode("Show All Lines");
newOption.appendChild(newOptionTitle);
for (i = 0; i < charNames.length; i++) {
newOption = document.createElement("option");
selectBox.appendChild(newOption);
newOptionTitle = document.createTextNode(charNames[i]);
newOption.appendChild(newOptionTitle);
}
}
function showLines() {
alert("The Box has been changed");
}
Every time the option in the box is changed, I want it to call 'showLines()'. However, every time I try to implement an event, I can only get it to trigger when the page loads, and never again thereafter. Any help would be greatly appreciated.
每次更改框中的选项时,我都希望它调用“showLines()”。然而,每次我尝试实现一个事件时,我只能让它在页面加载时触发,之后再也不会触发。任何帮助将不胜感激。
采纳答案by Anoop
selectBox.onchange = showLines;
should solve your problem.
selectBox.onchange = showLines;
应该可以解决您的问题。
in some browsers onchange get fired only after blurring select box. to over come this you can use onclick
instead of onchange
在某些浏览器中 onchange 只有在模糊选择框后才会被触发。克服这个你可以使用onclick
而不是onchange
回答by Niet the Dark Absol
My guess is that you're doing this:
我的猜测是你正在这样做:
selectBox.onchange = showLines();
If that's the case, just remove the ()
:
如果是这种情况,只需删除()
:
selectBox.onchange = showLines;
回答by Pravesh Sirohi
When I pass dynamically id in case then what I do:
当我动态传递 id 时,我会做什么:
var selectcell = tablerow.insertCell(1);
var selectelmt = document.createElement('select');
selectelmt.name = 'Select';
selectelmt.value = 'select';
selectelmt.classList = 'form-control input-sm cobclass';
selectelmt.onchange= onselectchange(i);
selectelmt.id = 'cobselect' + i;
selectelmt.options[0] = new Option('select');
selectcell.appendChild(selectelmt);
// ddrbind(i);
show();
i++;`