Javascript 选择文档背景颜色的“选择列表”选项时如何更改该颜色

Javascript 选择文档背景颜色的“选择列表”选项时如何更改该颜色,javascript,select,background-color,Javascript,Select,Background Color,功能更改\u颜色(){ var getSelect=document.getElementsByName(“colorPick”); var selection=getSelect.options[getSelect.selectedIndex].value; 对于(i=0;i

功能更改\u颜色(){
var getSelect=document.getElementsByName(“colorPick”);
var selection=getSelect.options[getSelect.selectedIndex].value;
对于(i=0;i

背景色
蓝色
青色
白色

您的代码不起作用,因为返回元素的节点列表集合。您需要访问其中一个元素,因为无法获取集合的值

document.getElementsByName("colorPick")[0]; // First element

您可以通过传递select元素的上下文来避免这种情况:
onchange=“change\u color(this)”

在更改背景色方面,您需要将
主体
元素的背景色设置为所选元素的文本。不是价值

功能更改\u颜色(选择){
var color=select.options[select.selectedIndex].textContent;
document.body.style.backgroundColor=颜色;
}

背景色
蓝色
青色
白色
它的工作原理如下:

<body>
<select name="colorPick" onchange="change_color();">
<option value="0">Background Color</option>
<option value="Blue">Blue</option>
<option value="Cyan">Cyan</option>
<option value="White">White</option>
</select>
</body>

背景色
蓝色
青色
白色
javascript:

function change_color() {
    var getSelect = document.getElementsByName("colorPick");
    var selection = getSelect[0].options[getSelect[0].selectedIndex].value;
    for (i = 0; i < getSelect[0].options.length; i++) {
        document.body.style.backgroundColor = selection;
    }
}
功能更改\u颜色(){
var getSelect=document.getElementsByName(“colorPick”);
var selection=getSelect[0]。选项[getSelect[0]。selectedIndex]。值;
对于(i=0;i