如何在JavaScript中模拟target =“ _ blank”

2020/10/31 13:03 · javascript ·  · 0评论

当用户单击链接时,我需要更新数据库中的字段,然后在新窗口中打开请求的链接。更新没有问题,但是我不知道如何在不要求他们单击另一个超链接的情况下打开新窗口。

<body onLoad="document.getElementById('redirect').click">
<a href="http://www.mydomain.com?ReportID=1" id="redirect" target="_blank">Report</a>
</body>

<script>
    window.open('http://www.example.com?ReportID=1', '_blank');
</script>

第二个参数是可选的,是目标窗口的名称。

这可能有帮助

var link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
    link.href = 'http://www.google.com';
    link.target = '_blank';
    var event = new MouseEvent('click', {
        'view': window,
        'bubbles': false,
        'cancelable': true
    });
    link.dispatchEvent(event);

我知道这是完成的工作,但是这是我用来解决应用程序中问题的方法。

if (!e.target.hasAttribute("target")) {
    e.preventDefault();     
    e.target.setAttribute("target", "_blank");
    e.target.click();
    return;
}

基本上,这里发生的是我检查链接是否具有target=_blank属性。如果不是,它将停止触发链接,将其设置为在新窗口中打开,然后以编程方式单击它。

通过尝试以下操作,您可以进一步前进并跳过停止原始单击的操作(并使代码紧凑得多):

if (!e.target.hasAttribute("target")) {
    e.target.setAttribute("target", "_blank");
}

如果您使用jQuery来抽象添加跨浏览器属性的实现,则应使用此方法代替e.target.setAttribute("target", "_blank")

    jQuery(event.target).attr("target", "_blank")

You may need to rework it to fit your exact use-case, but here's how I scratched my own itch.

Here's a demo of it in action for you to mess with.

(The link in jsfiddle comes back to this discussion .. no need a new tab :))

I personally prefer using the following code if it is for a single link. Otherwise it's probably best if you create a function with similar code.

onclick="this.target='_blank';"

I started using that to bypass the W3C's XHTML strict test.

This is how I do it with jQuery. I have a class for each link that I want to be opened in new window.

$(function(){

    $(".external").click(function(e) {
        e.preventDefault();
        window.open(this.href);
    });
});

You can extract the href from the a tag:

window.open(document.getElementById('redirect').href);

This might help you to open all page links:

$(".myClass").each(
     function(i,e){
        window.open(e, '_blank');
     }
);

It will open every <a href="" class="myClass"></a> link items to another tab like you would had clicked each one.

You only need to paste it to browser console. jQuery framework required

本文地址:http://javascript.askforanswer.com/ruhezaijavascriptzhongmonitarget-_-blank.html
文章标签:
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!