当用户点击链接时,我需要更新数据库中的字段,然后在新窗口中打开请求的链接。 更新没有问题,但是我不知道如何在不要求他们点击另一个超链接的情况下打开一个新窗口。
<body onLoad="document.getElementById('redirect').click">
<a href="http://www.mydomain.com?ReportID=1" id="redirect" target="_blank">Report</a>
</body>
当用户点击链接时,我需要更新数据库中的字段,然后在新窗口中打开请求的链接。 更新没有问题,但是我不知道如何在不要求他们点击另一个超链接的情况下打开一个新窗口。
<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>
第二个参数是可选的,是目标窗口的名称。
window.open
的作用与 target="_blank"
相同 - 它会在新窗口中打开 URL。 - ceejayoz这可能有所帮助
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")
:
e.target.setAttribute(“target”,“_blank”)
: jQuery(event.target).attr("target", "_blank")
你可能需要重新调整它以适应你的具体用例,但这就是我满足自己需求的方法。以下是我使用jQuery的方法。我为想要在新窗口中打开的每个链接创建一个类。
$(function(){
$(".external").click(function(e) {
e.preventDefault();
window.open(this.href);
});
});
如果只是针对单个链接,我个人更喜欢使用以下代码。否则,最好使用类似代码创建一个函数。
onclick="this.target='_blank';"
window.open(document.getElementById('redirect').href);
<button type="button" onclick="newTab('http://google.com')">search</button>
<button type="button" onclick="newTab('http://amazon.com')">buy</button>
<button type="button" onclick="newTab('http://gmail.com')">read</button>
<script>
function newTab(url) {
window.open(url, '_blank');
}
</script>
someElement.addEventListener('click', (e) => {
if (e.shiftKey) {
// Shift down + window.open() requires a "timeout" wrapper
// Else a "new window" opens instead of a new tab
setTimeout(() => window.open(url, '_blank'))
} else {
// if shift is not down this will open a new tab
window.open(url, '_blank')
}
}
JS的变化(href='#' target='_blank')
target="_top"
不会在新窗口中打开 -target="_blank"
会。 - Tomalak