在新标签页中打开每个链接

我知道我可以通过将 target _blank 属性添加到锚标记来在新选项卡中打开链接。

但是有什么办法可以触发我网站上的每个链接在新标签页中打开吗?


当年话下
浏览 121回答 4
4回答

MMTTMM

您只是在寻找CSS 解决方案吗?或任何类似下面的解决方案(JQuery)$('a').click(function()&nbsp;{ &nbsp;&nbsp;$(this).attr('target',&nbsp;'_blank'); });head你也可以在你的标签中添加下面的代码-<base&nbsp;target="_blank">这将使所有a标签在新选项卡中打开

慕仙森

这是 JS 示例并与onclick处理程序一起使用<div onclick="openInNewTab('www.example.com');">Click</div>function openInNewTab(url) {  var win = window.open(url, '_blank');  win.focus();}

呼如林

您可以使用 html 属性打开指向新选项卡的所有链接target="_blank"只需复制javascript代码并放置:&nbsp;window.onload = function(){&nbsp; &nbsp; &nbsp; &nbsp; var a = document.getElementsByTagName('a');&nbsp; &nbsp; &nbsp; &nbsp; for (var i=0; i<a.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a[i].setAttribute('target', '_blank');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }或者您可以使用jQuery代码:在使用这个之前请确保你在你的项目中添加了 jquery。$(document).ready(function(){&nbsp; &nbsp; $("a").attr("target", "_blank");});

莫回无

您可以在循环中使用 Vanilla JavaScript FOR:let links = document.links;for (let i = 0; i < links.length; i++) {&nbsp; &nbsp; if (links[i].hostname != window.location.hostname) {&nbsp; &nbsp; &nbsp; &nbsp; links[i].target = '_blank';&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript