javascript 如何将选定的下拉值传递给更改 onclick 背景颜色的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16180639/
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
How to pass a selected drop down value to a function that changes background color onclick
提问by Joe
<script>
myVar = document.getElementById('colorpick').value;
function color_click(myVar){
document.getElementById("touch").style.backgroundColor=myVar;
}
</script>
<select name="colorpick" id="colorpick">
<option value="red">red</option>
<option value="blue">blue</option>
<option value="green">green</option>
</select>
<div id="touch" onclick="color_click(myVar);"> XXXXXXXXXXX </div>
This code works as expected when I substitute 'blue' for the value of myVar, however I want to choose which color via dropdown menu before I click the element to change it's background.
当我用“蓝色”代替 myVar 的值时,此代码按预期工作,但是我想在单击元素以更改其背景之前通过下拉菜单选择哪种颜色。
回答by Xiaodan Mao
Because you want to get the color via dropdown menu when you click the div, so you need to put
因为你想在点击div时通过下拉菜单获取颜色,所以你需要把
myVar = document.getElementById('colorpick').value;
in the color_click function.
You can try this:
在 color_click 函数中。
你可以试试这个:
function color_click(){
var myVar = document.getElementById('colorpick').value;
document.getElementById("touch").style.backgroundColor = myVar;
}
And in you div:
在你的div中:
<div id="touch" onclick="color_click();"> XXXXXXXXXXX </div>
Hope it's helpful.
希望它有帮助。
回答by ryanbrill
You need to access the value of the selected option. To do that, you need something like this:
您需要访问所选选项的值。要做到这一点,你需要这样的东西:
function color_click(){
var sel = document.getElementById('colorpick'),
myVar = sel.options[sel.selectedIndex].value;
document.getElementById("touch").style.backgroundColor=myVar;
}