首页 > 解决方案 > 如何使用 window.open 在同一个选项卡中打开(使用 self 不起作用)

问题描述

我有一些自定义的长 JS 代码太长而无法发布,基本上当用户单击我网站上的按钮时,它正在创建一个自定义<form>,并将其作为 POST 请求提交到一个打开的新选项卡中。

我想修改它以在同一个选项卡中打开。相关的代码行是:

w = window.open("",'myPop_Window' + wId);

我尝试将其更改为:

w = window.open("",'myPopup_Window' + wId, "_self");

但它没有用。

我希望这是足够的信息来弄清楚如何修改该行以在同一选项卡中打开。

编辑:

更多表单创建代码:

var tryOpenTab2 = function(button,tab_url,tab_url_data_g) {
    var data = {};
    var form = button.parents('form').first();
    if (form.length > 0)
        data = getFormData(form);
    if (tab_url_data_g) {
        data['g'] = tab_url_data_g
    }

    if (!tab_url)
        return;

    var form = $('<form></form>');
    
    form.attr('method', 'POST');
    
    form.attr('action', tab_url);
    for (var k in data) {
        var input = $('<input />');
        input.attr('type', 'hidden');
        input.attr('name', k);
        input.attr('value', data[k]);
        form.append(input);
    }
    $('body').append(form);

    if (w && !w.closed) {
        //w.close();// client want to always open new tab
        w = null;
    }
 
        wId = ''+new Date().getTime();
        
 
        w = window.open("",'myPopup_Window' + wId); 
 
    
        form.attr('target', 'myPopup_Window' + wId);
 
    }

编辑2:

我应该如何wId在新代码中使用?

if (button.is(button_class3)) {
    w = window.open(window.location.href.split('#')[0] + "#" + button.attr("data-popup-id"));
} else {
    wId = ''+new Date().getTime();
    
  if(  (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))) {  
    
    // w = window.open("",'myPopup_Window' + wId);   old line
    
    w = window.open("","_self") // new line 1
    form.attr('target', '_self'); // new line 2
    
}
else { // non mobile agent - use blank
    w = window.open('about:blank','myPopup_Window' + wId);
    
    form.attr('target', 'myPopup_Window' + wId);

}

标签: javascript

解决方案


我怀疑您可以从提交过程中删除 tryOpenTab2 并让表单正常提交而没有目标

否则试试这个

改变

if (w && !w.closed) {
  //w.close();// client want to always open new tab
    w = null;
}
wId = ''+new Date().getTime();
w = window.open("",'myPopup_Window' + wId); 
form.attr('target', 'myPopup_Window' + wId);

 form.attr('target', '_self');

推荐阅读