You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在下拉菜单中实现iframe加载与target_blank新标签页打开

解决方案

<option>元素本身不支持target属性,所以你添加的target="_blank"不会生效。我们可以通过自定义数据属性标记需要在新标签页打开的链接,再修改JavaScript逻辑区分处理两种场景:

1. 修改HTML中的<option>标签

给需要新标签页打开的选项添加data-target="_blank"自定义属性,示例如下:

<optgroup label="Your Hosting Account:">
  <option value="https://login.ionos.com/" data-target="_blank">IONOS Hosting</option>
</optgroup>

2. 更新JavaScript的setIframeSource函数

修改函数逻辑,先判断选中选项的自定义属性:如果是_blank则用window.open打开新标签页,否则加载到iframe中:

function setIframeSource() {
    var theSelect = document.getElementById('location');
    var selectedOption = theSelect.options[theSelect.selectedIndex];
    var theUrl = selectedOption.value;
    var target = selectedOption.getAttribute('data-target');
    
    if (target === '_blank') {
        window.open(theUrl, '_blank');
        // 可选:重置下拉菜单到默认选项,避免重复点击重复打开标签页
        theSelect.selectedIndex = 0;
    } else {
        var theIframe = document.getElementById('preview-frame');
        theIframe.src = theUrl;
    }
}

修改后的核心代码片段

下拉菜单HTML

<select name="location" id="location" onchange="setIframeSource()">
    <option value="https://saviodesigns.com/EasyAdmin/">Select a Module...</option>
    <optgroup label="Your Site's Modules:">
        <option value="../admin_cms/">PowerCMS</option>
        <option value="../webadmin/">Gallery Manager Pro</option>
    </optgroup>
    <optgroup label="Your Hosting Account:">
        <option value="https://login.ionos.com/" data-target="_blank">IONOS Hosting</option>
    </optgroup>
</select>

处理逻辑JavaScript

function setIframeSource() {
    var theSelect = document.getElementById('location');
    var selectedOption = theSelect.options[theSelect.selectedIndex];
    var theUrl = selectedOption.value;
    var target = selectedOption.getAttribute('data-target');
    
    if (target === '_blank') {
        window.open(theUrl, '_blank');
        theSelect.selectedIndex = 0;
    } else {
        var theIframe = document.getElementById('preview-frame');
        theIframe.src = theUrl;
    }
}

补充说明

  • data-*自定义属性是HTML5规范支持的标准写法,兼容性覆盖所有现代浏览器。
  • 重置下拉菜单的代码可以提升用户体验,避免用户重复选中同一外部链接时多次打开标签页。

内容的提问来源于stack exchange,提问作者Chris Knabenshue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 16:35:15