从下拉列表调用javascript函数

时间:2013-01-15 00:49:50

标签: javascript html

我现在有这个HTML代码:

Theme
<ul id="dropdown">
    <li> Choose theme
        <ul> 
            <li id="stylesheet1" > <a href="#"> Default </a></li>
            <li id="stylesheet2" > <a href="#"> Theme 1 </a></li>
            <li id="stylesheet3" > <a href="#"> Theme 2 </a></li>
            <li id="stylesheet4" > <a href="#"> Theme 3 </a></li>

        </ul>
    </li>
</ul> 

在另一个javascript文档中,我有这段代码:

function initate()
{

document.getElementById("myList").onchange = function() {
   var sheet=document.getElementById("myList").value;

   if(sheet=="one"){
   setActiveStyleSheet("theme1");
   }
   else if(sheet=="two"){
   setActiveStyleSheet("theme2");
   }
   else if(sheet="three"){
   setActiveStyleSheet("theme3");
   }
   else{
   setActiveStyleSheet("default");
   }
   return false
};

}

window.onload = initate;

现在这很好用,但我没有上面使用的下拉菜单,而是想使用这个HTML代码:

Select Theme
<form>
<select id="myList" >
  <option id="stylesheet1">Default</option>
  <option id="stylesheet2">Theme 1</option>
  <option id="stylesheet3">Theme 2</option>  
  <option id="stylesheet4">Theme 3</option>
</select>
<form>

和以前一样,我想在我单独的javascript文档中使用我的事件处理程序。我试图将我的javascript替换为这些函数:

document.getElementById("stylesheet1").onchange = function() {
   setActiveStyleSheet("default");
   return false
};

但它不起作用。你如何以这种方式纠正呼叫功能?

2 个答案:

答案 0 :(得分:6)

演示:http://jsfiddle.net/zYMFa/

使用选项的值并处理选择的更改事件。 select的value属性获取所选选项的值,因此您可以在更改函数中使用this.value。

<form>
<select id="myList" >
  <option value="default">Default</option>
  <option value="theme1">Theme 1</option>
  <option value="theme2">Theme 2</option>  
  <option value="theme3">Theme 3</option>
</select>
<form>

document.getElementById("myList").onchange = function() {
   setActiveStyleSheet(this.value);
   return false
};

答案 1 :(得分:3)

<select id="myList" >
  <option id="stylesheet1" value="default">Default</option>
  <option id="stylesheet2" value="one">Theme 1</option>
  <option id="stylesheet3" value="two">Theme 2</option>  
  <option id="stylesheet4" value="three">Theme 3</option>
</select>

document.getElementById("myList").onchange = function() {
   var sheet=document.getElementById("myList").value;

   if(sheet=="one"){
   setActiveStyleSheet("theme1");
   }
   else if(sheet=="two"){
   setActiveStyleSheet("theme2");
   }
   else if(sheet=="three"){
   setActiveStyleSheet("theme3");
   }
   else{
   setActiveStyleSheet("default");
   }
   return false
};