2013-02-09 36 views
0

我一直在潜伏,找不到答案。基本上我有一堆按钮,我想变成一个下拉菜单,并执行代码onChange。但是,我是JavaScript新手,我很难弄清楚这是如何工作的。我有点工作,但我不能让它与多个选项一起工作。下面是我有:使用选项执行一些JavaScript onChange?

<button class="lightbutton" onclick="lightswitch(1,true);lightswitch(2,true);lightswitch(3,true);"> 
All lights on</button> 
<button class="lightbutton" onclick="lightswitch(1,false);lightswitch(2,false);lightswitch(3,false);"> 
All lights off</button> 

我的灯光做这个开启:

<form name="functions"> 
<select name="jumpmenu" onChange="lightswitch(1,true);lightswitch(2,true);lightswitch(3,true);"> 
<option>LightFunctions</option> 
<option value="*";>Light 1 On</option> 
<option value="*";>Light 1 Off</option> 
</select> 
</form> 

现在,我明白为什么它的工作原理 - 它只是告诉它,每当它改变开启所有的灯。但是,如何更改“onChange”以使其成为我选择的选项?

我想我错过了一些JS但不确定。

我很感激帮助。

+0

'light 1 on'选项与'light 1 off'有什么不同?什么改变? – 2013-02-09 22:42:32

+0

所以基本上我在做什么是我有飞利浦色调光设置和关闭光1,理论上,将关闭灯,然后打开将它打开。 – ElRojito 2013-02-09 22:51:22

回答

2

为了有选择元素控制只是第一个电灯开关,你可以这样做:

<select name="jumpmenu" onChange="lightswitch(1,this.value==='on');"> 
<option value="on";>Light 1 On</option> 
<option value="off";>Light 1 Off</option> 
</select> 

也就是说,而不是硬编码true作为第二个参数lightswitch()测试选择元素的当前值。 (请注意,我已经改变属性的值,以更有意义。表达this.value==='on'将评估要么truefalse。)

在选择的onChange属性this将参考选择元素本身。

编辑:要有相同的选择控制多个参数,您可以添加一些data-属性的选项元素,以根据需要存储每个选项的额外参数(在这种情况下,我认为你只需要一个额外的)。而且我要移动的逻辑出了内嵌属性:

<select name="jumpmenu" onChange="jumpChange(this);"> 
    <option value="">LightFunctions</option> 
    <option data-switchNo="1" value="on";>Light 1 On</option> 
    <option data-switchNo="1" value="off";>Light 1 Off</option> 
    <option data-switchNo="2" value="on";>Light 2 On</option> 
    <option data-switchNo="2" value="off";>Light 2 Off</option> 
    <option data-switchNo="3" value="on";>Light 3 On</option> 
    <option data-switchNo="3" value="off";>Light 3 Off</option> 
</select> 

function jumpChange(sel) { 
    if (sel.value === "") return; // do nothing if user selected first option 

    var whichLight = +sel.options[sel.selectedIndex].getAttribute("data-switchNo"); 
    lightswitch(whichLight, sel.value==='on'); 

    sel.value = ""; // reset select to display the "Light Functions" option 
} 

演示:http://jsfiddle.net/N7b8j/2/

在我添加的参数sel会选择元素(从onChange属性设置为thisjumpChange(sel)功能)。 “神奇”发生在这条线:

var whichLight = +sel.options[sel.selectedIndex].getAttribute("data-switchNo"); 

为了解释该行:sel.options[sel.selectedIndex]获取到当前选定的选项的引用,.getAttribute("data-switchNo")获取期权的data-属性。 +将属性从一个字符串转换为一个数字。

+0

你摇滚!是否还有一种方法可以让这个下拉菜单控制多个?像“lightswitch(*然后是某种类型的变量?我将尝试有一个下拉改变颜色,然后一个关闭和打开,第三个改变选择”场景“其实,1,2会做呃? – ElRojito 2013-02-09 22:53:15

+0

好的,我已经用一个fancier函数更新了我的答案,试试我的演示,你应该能够从那里推断出你的其他需求。 – nnnnnn 2013-02-09 23:13:56

+0

你一直在帮助很多,我真的很感激。 – ElRojito 2013-02-09 23:20:01

相关问题