使用onclick javascript函数下拉菜单

时间:2014-06-16 19:25:52

标签: javascript html function drop-down-menu

我正在尝试创建一个下拉菜单,在单击时调用JavaScript函数。我的下拉菜单是这样的:

<select name = "navyOp"> 
    <option selected = "selected">Select a Navy Op Area</option>
    <option value = "AN01">AN01</option>
    <option value = "AN02">AN02</option>
    <option value = "AN03">AN03</option>
</select>

因此,对于每个选项,我都希望调用特定的JavaScript函数。有一种简单的方法可以做到这一点吗?

4 个答案:

答案 0 :(得分:4)

您可以将事件侦听器附加到选择元素:

&#13;
&#13;
window.test = function(e) {
  if (e.value === 'AN01') {
    console.log(e.value);
  } else if (e.value === 'AN02') {
    console.log(e.value);
  } else if (e.value === 'AN03') {
    console.log(e.value);
  }
}
&#13;
<select name="navyOp" onchange="test(this);">
  <option selected="selected">Select a Navy Op Area</option>
  <option value="AN01">AN01</option>
  <option value="AN02">AN02</option>
  <option value="AN03">AN03</option>
</select>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

你可以试试这个

html更改或编辑:

<select name = "navyOp" id = "navyOp"> 

JavaScript的:

    document.getElementById("navyOp").onchange = function()
{

    if(this.value === "AN01")
    {
        //do this function
        alert("an01");
    }
    else if(this.value == "AN02")
    {
        //do this function
        alert("an02");
    }
    else if(this.value == "AN03")
    {
        alert("an03");
    }
};

答案 2 :(得分:1)

您可以添加每次更改值时调用的函数:

<强> HTML

<select name = "navyOp" onChange="myFunction()"> 
    <option selected = "selected">Select a Navy Op Area</option>
    <option value = "AN01">AN01</option>
    <option value = "AN02">AN02</option>
    <option value = "AN03">AN03</option>
</select>

<强> JS

var myDropdown=document.getElementsByName('navyOp')[0];

function myFunction(){
    alert('option changed : '+myDropdown.value);
}

JS Fiddle

答案 3 :(得分:0)

一种方法是

function expand(s)
{
  var td = s;
  var d = td.getElementsByTagName("div").item(0);

  td.className = "menuHover";
  d.className = "menuHover";
}

您必须为每个选项菜单执行此操作。希望这能回答你的问题