繁体   English   中英

如何在新窗口中打开链接?

[英]How can I open a link in a new window?

我有一个特定链接的点击处理程序,在里面我想做类似以下的事情:

window.location = url

我需要这个在新窗口中实际打开网址,我该怎么做?

你可以这样:

window.open('url', 'window name', 'window settings')

jQuery的:

$('a#link_id').click(function(){
  window.open('url', 'window name', 'window settings');
  return false;
});

您也可以将target设置为_blank

以下是如何在单击处理程序中强制执行目标:

$('a#link_id').click(function() {
    $(this).attr('target', '_blank');
});

您也可以使用jquery prop()方法。

$(function(){
  $('yourselector').prop('target', '_blank');
}); 

我刚刚找到了一个有趣的解决方案。 我创建的跨度包含基于Web服务返回的信息。 我想过试图在跨度上放一个链接,这样如果我点击它,“a”就会捕获点击。

但是我试图捕捉带有跨度的点击...所以我想在创建跨度时为什么不这样做。

var span = $('<span id="something" data-href="'+url+'" />');

然后我将一个点击处理程序绑定到跨度,该跨度根据'data-href'属性创建了一个链接:

span.click(function(e) {
    e.stopPropagation();
    var href = $(this).attr('data-href');
    var link = $('<a href="http://' + href + '" />');
    link.attr('target', '_blank');
    window.open(link.attr('href'));
});

这成功地允许我点击跨度并打开一个带有正确URL的新窗口。

<a href="myurl.html" target="_blank">My Link</a>什么问题? 不需要Javascript ......

此解决方案还考虑了url为空并禁用(灰色)空链接的情况。

 $(function() { changeAnchor(); }); function changeAnchor() { $("a[name$='aWebsiteUrl']").each(function() { // you can write your selector here $(this).css("background", "none"); $(this).css("font-weight", "normal"); var url = $(this).attr('href').trim(); if (url == " " || url == "") { //disable empty link $(this).attr("class", "disabled"); $(this).attr("href", "javascript:void(0)"); } else { $(this).attr("target", "_blank");// HERE set the non-empty links, open in new window } }); } 
 a.disabled { text-decoration: none; pointer-events: none; cursor: default; color: grey; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <a name="aWebsiteUrl" href="http://www.baidu.com" class='#'>[website]</a> <a name="aWebsiteUrl" href=" " class='#'>[website]</a> <a name="aWebsiteUrl" href="http://www.alibaba.com" class='#'>[website]</a> <a name="aWebsiteUrl" href="http://www.qq.com" class='#'>[website]</a> 

Microsoft IE不支持将名称作为第二个参数。

window.open('url', 'window name', 'window settings');

问题是window name 这将有效:

window.open('url', '', 'window settings')

Microsoft仅允许以下参数,如果使用该参数:

  • _空白
  • _媒体
  • _parent
  • _搜索
  • _自
  • _最佳

检查此Microsoft站点

请注意,是否要在click事件的事件处理函数内执行AJAX请求 出于某种原因,Chrome(可能还有其他浏览器)无法打开新的标签/窗口。

这不是一个非常好的修复,但它的工作原理:

CSS:

.new-tab-opener
{
    display: none;
}

HTML:

<a data-href="http://www.google.com/" href="javascript:">Click here</a>
<form class="new-tab-opener" method="get" target="_blank"></form>

使用Javascript:

$('a').on('click', function (e) {    
    var f = $('.new-tab-opener');
    f.attr('action', $(this).attr('data-href'));
    f.submit();
});

实例: http//jsfiddle.net/7eRLb/

暂无
暂无

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

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