【问题标题】:Handling DropDown Menu处理下拉菜单
【发布时间】:2011-12-28 15:33:34
【问题描述】:

我的 html 中有一个下拉菜单,我想要的是当菜单更改时,调用一个 JS 函数来发送选定的值。我现在拥有的是这样的:

HTML/PHP:

<select name="selectSquad" class="SquadWeaponSelector" id="selectSquad" onchange="javascript:showWeaponEditorWindow(this.form.selectSquad);">
<?PHP
   $max = $squadNumbers - 1;
   $i = 0;
   while($i <= $max){
      echo "<option value=\"".$names_split[$i]."\"/>".$names_split[$i]."</option>";
      $i++;
   }
?>
</select>

JavaScript - 我想要发生的事情:

function showWeaponEditorWindow(squad){
   if(squad == "A PHP Value - Jack"){
      alert("jack selected");
   }
}

我将如何实现这一目标?

【问题讨论】:

    标签: javascript select menu drop-down-menu


    【解决方案1】:

    试试这个, 你需要在你的条件下分配squad.value

    <select name="selectSquad" class="SquadWeaponSelector" id="selectSquad" onchange="showWeaponEditorWindow(this);">
    
    
    function showWeaponEditorWindow(squad){
       if(squad.value == "A PHP Value - Jack"){
         alert("jack selected");
      }
    }
    

    更新:

    您可以使用selectedIndex 来获取选定的菜单rember,菜单索引从0 开始;

    所以把squad.value改成

    (squad.selectedIndex == 1) 
    

    【讨论】:

    • 很高兴看到有人不直接跳到 jQuery 来完成简单的 javascript 任务
    • 谢谢大卫。如果我想使用值的位置怎么办? EG:如果选择了小队.position == 1
    • 之所以这样是因为我的下拉菜单是动态的......所以没有办法知道里面会有什么
    【解决方案2】:

    我建议您为此目的使用 jQuery。你可以写:

    $('#selectSquad').change(function(){
       var selectedValue = $(this).val();
       // Do anything here with the selectedValue variable
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多