javascript - 为什么超链接无法在新选项卡中打开?

标签 javascript jquery html hyperlink

我有3个html文件: force_hyperlink_open_in_new_window.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Force hyperlink open in new window</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

</head>
<body>
<a href="force_hyperlink_open_in_new_window_01.html">Foo</a>
<a href="force_hyperlink_open_in_new_window_02.html">Bar</a>

<script type="text/javascript">
    $('a[href^="http://"]')
            .not('[target="_blank"]')
            .attr('target', '_blank');
</script>

</body>
</html>

force_hyperlink_open_in_new_window_01.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>01</title>
    <style>
        body{
            background-color: tomato;
        }
    </style>
</head>
<body>
</body>
</html>

force_hyperlink_open_in_new_window_02.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>02</title>
    <style>
        body{
            background-color: limegreen;
        }
    </style>
</head>
<body>
</body>
</html>

为什么 2 个超链接无法在新标签页中打开(我使用 Google Chrome 版本 52.0.2743.116(64 位))?

最佳答案

您选择以 http:// 开头的 anchor ,而您的链接是相对的并且不以 http:// 开头。

将 JQuery 选择器更改为常规 anchor :$('a'),它将添加您的目标(如果他们还没有)。请参阅https://jsfiddle.net/k7ww81ee/

$('a')
        .not('[target="_blank"]')
        .attr('target', '_blank');

关于javascript - 为什么超链接无法在新选项卡中打开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39064745/

相关文章:

javascript - 为使用节点appendChild添加的列表创建事件监听器

javascript - 将文本 float 到其容器的末尾

javascript - 根据 PHP 的输出执行 Javascript 的正确方法

javascript - 当您尝试在表单上键入内容时,html5 背景视频会全屏显示

html - 文本对齐不适用于 img

javascript - GWT 图形库

jquery - tinymce ajax表单上的空白内容提交?

java - 从URL下载xml文件进行解析

javascript - 需要同步 pouchDB 数据库的解决方案

html - 一旦我删除这个 div,div 就会离开位置