[英]Open a page in a new tab with JS
我正在将一些<ul>
转换为小型设备的<select>
,如下所示:
$("#blog aside .widget, #blog-single aside .widget").each(function() {
var widget = $(this);
$("<select />").appendTo(widget);
/* option en blanco*/
$("<option />", {
"value" : '',
"text" : widget.find('h3').text()+'..'
}).appendTo(widget.find('select'));
widget.find('ul li a').each(function(){
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo(widget.find('select'));
});
});
我想在新标签页中打开此链接,这就是我正在尝试的方式:
$("#blog select, #blog-single select").change(function() {
var url = $(this).find("option:selected").val();
/* simulamos target _blank, ya que son externos */
var a = document.createElement('a');
a.href= url;
a.className = 'external';
a.target = '_blank';
document.body.appendChild(a);
a.click();
});
似乎在Firefox中可以完成这项工作,但是在chrome中,我收到了弹出式窗口警告(它不认为用户单击而不是用JS模拟它)
任何解决方法?
为了避免您可以使用表格来调用屏幕
$("#blog select, #blog-single select").change(function() {
var url = $(this).find("option:selected").val();
/* simulamos target _blank, ya que son externos */
var form = document.createElement('form');
form.action= url;
form.method = 'get';
form.target = '_blank';
document.body.appendChild(form);
form.submit();
setTimeout(function(){
document.body.removeChild(form);
},1000);
});
这就是我们最终“解决”它的方式,
检查弹出窗口是否存在,如果不存在,则退回到当前选项卡:
var url = $(this).val();
var win = window.open(url);
/* Detectar posible bloqueo de popups */
if (win == null || typeof(win) == "undefined" || (win == null && win.outerWidth == 0) || (win != null && win.outerHeight == 0) || win.test == "undefined"){
window.location.href = url;
}else if (win){
win.onload = function(){
if (win.screenX === 0) {
win.close();
}
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.