Javascript 选择选项 onclick 更改 url 或更改 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7719367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:20:24  来源:igfitidea点击:

select option onclick change url or change div

javascripturlhtmlonclickonchange

提问by ciprian

So what i am trying to do is that in the moment i pick first option, to show a div, if i pick option 2 to redirect me to another url. i don't even know if it's possible! sample:

所以我想要做的是,在我选择第一个选项的那一刻,显示一个 div,如果我选择选项 2 将我重定向到另一个 url。我什至不知道这是否可能!样本:

<select class="required" id="thechoices">
<option value="">Service Type</option>
<option value="box1">From LAX Airport</option>
<option VALUE="http://www.dma.org/linuxsig/">To The Airport</option>
</select>

<div id="box1"><p>Box 1 stuff...</p></div>

采纳答案by kchason

<select id="options" onchange="optionCheck()">
 <option></option>
 <option value="show">Show Div</option>
 <option value="goto">Go To Google</option>
 </select>
<div id="hiddenDiv" style="height:100px;width:300px;border:1px;visibility:hidden;">
I am visible now!</div>

<script type="text/javascript">
    function optionCheck(){
        var option = document.getElementById("options").value;
        if(option == "show"){
            document.getElementById("hiddenDiv").style.visibility ="visible";
        }
        if(option == "goto"){
            window.location = "http://google.com";
        }
    }
</script>

You can make it a lot prettier with jquery, but this should work.

你可以用 jquery 让它更漂亮,但这应该有效。

回答by david

Yes it is possible

对的,这是可能的

Add onchange event handler to your select.

将 onchange 事件处理程序添加到您的选择中。

<select class="required" id="thechoices" onchange="return airportChoice(this)">

Set the display for the box ID you wish to hide to hidden.

将要隐藏的框 ID 的显示设置为隐藏。

   #box1{display:none} //css

Here is a generic function that recives argument based on reference, Based on your question so you can easly have lots of to an from airport choices just add the below to each of your selects if you need more choices.

这是一个基于参考接收参数的通用函数,基于您的问题,因此您可以轻松地从机场选择很多,如果您需要更多选择,只需将以下添加到您的每个选择中。

 onchange="return airportChoice(this)" 

JS function

JS函数

function airportChoice(n){

  if(n.selectedIndex === 1){
  // show a div (id)  // alert(n.value);
    document.getElementById(n.value).style.display = "block";
   }else if(n.selectedIndex === 2){
     location.href= n.value;  // redirect the user to the url 
   }
    // this last one is not what you ask but for completeness 
    // hide the box div if the first option is selected again
    else if (n.selectedIndex == 0){ // alert(n[1].value);
    document.getElementById(n[1].value).style.display = "none";
    }
  }