制作在新窗口中打开的下拉框链接

making dropdown boxes links that open in a new window

本文关键字:链接 在新窗口中打开      更新时间:2023-09-26

所以我在这里找到了这个代码:

<select id="my_selection">
<option value="x" href="/link/to/somewhere">value 1</option>
<option value="y" href="/link/to/somewhere/else">value 2</option>
</select>
<script>
document.getElementById('my_selection').onchange = function() {
    window.location.href = this.children[this.selectedIndex].getAttribute('href');
}
</script>

它的工作原理很好,它把下拉框项目变成了链接。我想知道是否有办法在新窗口中打开这些链接,而不仅仅是重定向?我刚刚进入编码/编程领域,所以我很难处理许多大多数有经验的程序员认为理所当然的简单事情。谢谢

将我的注释转换为答案
请注意"请选择"以允许选择第一个URL。

<select id="my_selection">
  <option value="">Please select</option>
  <option value="/link/to/somewhere">value 1</option>
  <option value="/link/to/somewhere/else">value 2</option>
</select>

使用

window.onload=function() {
  document.getElementById('my_selection').onchange = function() {
    var href= this.value;
    if (href) {
      var win = window.open(href,"_blank");
    }
  }
}

您应该使用

window.open 

代替

window.location.href

有关window.open的详细信息,请查看http://www.w3schools.com/jsref/met_win_open.asp

document.getElementById('my_selection').onchange = function() {
window.open (this.children[this.selectedIndex].getAttribute('href'));
}

这应该是你想要的,它会在一个新的选项卡/窗口中打开链接。