我的链接是 JavaScript 函数,它显示加载程序,然后导航到目标链接:
<script>
function go(url) {
document.body.innerHTML = "some loader html";
window.location = url;
}
</script>
<a href="javascript:go('test.php');">Click here</a>
但是,当用户右键单击它并想要在新选项卡中导航到 test.php
时,此链接将不起作用。
我希望当用户想要在新选项卡/窗口中打开链接时该链接也能起作用。有没有一种 javascript/jquery 方法可以实现这一点?
谢谢
最佳答案
您的链接应该是链接,而不是 JavaScript 函数。它们的主要目的是导航。您可以稍后在点击处理程序中添加额外的行为:
document.body.addEventListener('click', evt => {
const link = evt.target.closest('a.use-loader');
if (!link) return;
evt.preventDefault();
document.body.innerHTML = '<h1 style="color:red">LOADING</h1>';
window.location.href = link.href;
});
<a href="https://example.com" class="use-loader">
This loads <em>really slow</em>, and it's my responsibility to fix that.
</a>
<br>
<a href="https://example.org" class="use-loader">This one, too.</a>
或者使用 jQuery:
$('body').on('click', 'a.use-loader', function () {
document.body.innerHTML = '<h1 style="color:red">LOADING</h1>';
window.location.href = $(this).attr('href');
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://example.com" class="use-loader">
This loads <em>really slow</em>, and it's my responsibility to fix that.
</a>
<br>
<a href="https://example.org" class="use-loader">This one, too.</a>
这样,链接仍然适用于任何未运行 JavaScript 的代理,包括打开新选项卡的浏览器和运行 NoScript 的用户。
关于javascript - 右键启用 "open in new tab/window",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55817382/