简体   繁体   English

基于下拉的Onclick按钮href

[英]Onclick button href based on drop-down

Premise: 前提:

In this particular example, I am trying to make a selection in a drop-down menu and change the keyword 'something' in the onclick() handler mentioned below with whatever value is associated with the selection made in #panel_link_library . 在此特定示例中,我试图在下拉菜单中进行选择,并使用与#panel_link_library中进行的选择相关的任何值来更改下面提到的onclick()处理程序中的关键字'something' Hope this makes sense? 希望这有意义吗?

Code so far: 到目前为止的代码:

 var aaa = document.getElementById('panel_link_library') aaa.onchange = function() { document.getElementById("abc").href = this.value } 
 <div class="dropdown-plans"> <select id="panel_link_library" name="p_links"> <option value="/pages/home_up/">Location 1</option> <option value="www.google.com">Location 2</option> <option value="https://321.com">Location 3</option> </select> </div> <div id="abc" class="panel_link" onclick="location.href='something'">Jump to location</div> 

Solution: 解:

Your onclick simply needs to read the value of the selection! 您的onclick只需读取选择的值!

 const navToSelection = _ => { const el = document.getElementById("panel_link_library") const val = el.options[el.selectedIndex].value window.location.href = val // That's it! } 
 <div id="abc" class="panel_link" onclick="navToSelection()">Jump to location</div> 

Explanation: 说明:

  • We first fetch the dropdown element by it's id = panel_link_library 我们首先通过id = panel_link_library获取dropdown元素
  • Then we get that elements selected element, and from that read its value property 然后,我们将该元素选择为元素,并从中读取其value属性
  • Use this to then set as the new location for your browser to navigate to 然后使用它设置为浏览器导航到的新位置

Change the location at the onclick function, then you can go and get the dropbox value and redirect the user. 在onclick函数上更改位置,然后您可以获取保管箱值并重定向用户。

Hope this is what you were looking for. 希望这就是您想要的。 Happy to explain or help in a better solution if needed. 如果需要,很高兴为您解释或提供更好的解决方案。

 var aaa = document.getElementById('panel_link_library'); function goToSomewhere() { window.location.href= aaa.value; } 
 <div class="dropdown-plans"> <select id="panel_link_library" name="p_links"> <option value="/pages/home_up/">Location 1</option> <option value="https://www.google.com">Location 2</option> <option value="https://321.com">Location 3</option> </select> </div> <div id="abc" class="panel_link" onclick="goToSomewhere()">Jump to location</div> 

You're trying to assign an href to a div. 您正在尝试将href分配给div。 assign it to the onclick handler. 将其分配给onclick处理程序。

var aaa = document.getElementById('panel_link_library');
  aaa.onchange = function (e) {
    console.log(e);
    var abc = document.getElementById("abc");
    abc.addEventListener('click', () => {window.location = e.target.value});
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM