[英]Change color of a table cell using javascript dropdown menu
I'd like some help in creating a dropdown menu that changes the background color of one cell of a table. 我需要一些帮助来创建一个下拉菜单,以更改表格中一个单元格的背景颜色。 The code that I have below works, but only for a list of pre-defined options.
我下面的代码有效,但仅适用于预定义选项的列表。 The existing code listed below:
现有代码如下:
<form name="bgcolorForm">Try it now:
<select onChange="if(this.selectedIndex!=0)
document.getElementById('mycell').bgColor=this.options[this.selectedIndex].value">
<option value="choose">set background color
<option value="FFFFCC">light yellow
<option value="CCFFFF">light blue
<option value="CCFFCC">light green
<option value="CCCCCC">gray
<option value="FFFFFF">white
</select></form>
<table>
<tr>
<td id = "mycell">Cell One</td>
<td>Cell Two</td>
</tr>
</table>
I would like to modify this code such that it references a list of values (HTML color names) contained in an existing list. 我想修改此代码,使其引用现有列表中包含的值(HTML颜色名称)列表。 For instnace, instead of listing the option values, I have:
对于实例,我没有列出选项值,而是:
<select name="bg_color" id="bg_color" onchange=...>
I am having trouble with writing the "onchange" portion of the code. 我在编写代码的“ onchange”部分时遇到了麻烦。 I think that I need to create a variable in order to do this... I think I need to get to .text portion because my dropdown list contains color names like "red, blue, green, etc."
我认为我需要创建一个变量才能执行此操作...我认为我需要进入.text部分,因为我的下拉列表包含“红色,蓝色,绿色等”之类的颜色名称。 Below is how I was trying to accomplish this.
以下是我尝试完成此操作的方式。
<script type="text/javascript">
var e = document.getElementById("bg_color");
var newcolor = e.options[e.selectedIndex].text;
</script>
Am I on the right track? 我在正确的轨道上吗? Please let me know how you would accomplish this.
请让我知道您将如何完成此任务。
Also, I'm curious on if I wanted to apply this to a within the what additional changes would I have to make? 另外,我很好奇我是否想将此应用到范围内,我还需要进行哪些其他更改?
You forgot to put # for colors => #FFFFCC 您忘记为颜色放##= #FFFFCC
Try with that: 试试看:
<option value="#FFFFCC">light yellow
<option value="#CCFFFF">light blue
<option value="#CCFFCC">light green
<option value="#CCCCCC">gray
<option value="#FFFFFF">white
You can simplify your code by using jquery, it will also avoid you a lot of other cross browser javascript headaches. 您可以使用jquery简化代码,也可以避免其他很多跨浏览器javascript的麻烦。 I have put together a sample using your form here.
我在这里用您的表格整理了一个样本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.