javascript 根据 href 将 <a> 目标更改为“_blank”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3621742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:45:45  来源:igfitidea点击:

change <a> target to "_blank" depending on href

javascripthreftargetgetelementsbytagname

提问by Christian

I'm trying to sort through the links on my page and make some of them open into a new window, depending on their URL. This is the code I have. It doesn't seem to be working. Can you see why?

我正在尝试对页面上的链接进行排序,并根据其 URL 将其中一些链接打开到新窗口中。这是我的代码。它似乎不起作用。你能明白为什么吗?

function MakeMenuLinksOpenInNewWindow() {
    var links = document.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++) {
        if (links[i].href == "http://testtesttest.org/")
            links[i].target = "_blank";
    }
}
MakeMenuLinksOpenInNewWindow();

采纳答案by James Curran

Use jQuery.js. It'll make your life much easier:

使用 jQuery.js。它会让你的生活更轻松:

$("a[href='http://testtesttest.org/']").attr("target", "_blank");

回答by Darin Dimitrov

Make sure that when you call this function the DOM has been loaded:

确保在调用此函数时 DOM 已加载:

window.onload = MakeMenuLinksOpenInNewWindow;

or:

或者:

<body onload="MakeMenuLinksOpenInNewWindow();">

回答by David Murdoch

You should probably not be setting this javascript. And instead use HTML.

您可能不应该设置此 javascript。而是使用 HTML。

But if you must...

但如果你必须...

function MakeMenuLinksOpenInNewWindow() {
    var links = document.getElementsByTagName("a");
    for (var i = 0, l = links.length; i < l; i++) {
        if (links[i].href === "http://www.example.com/")
            links[i].target = "_blank";
    }
}
window.onload = MakeMenuLinksOpenInNewWindow;

回答by lincolnk

your javascript looks fine. assuming you're having problems with your link elements not existing before you try to modify them, you need to delay running your method as mentioned in other posts. my preferred method is moving the script contents to the end of the page.

你的 javascript 看起来不错。假设您在尝试修改链接元素之前遇到了不存在的问题,您需要像其他帖子中提到的那样延迟运行您的方法。我的首选方法是将脚本内容移动到页面的末尾。

since it looks like you're using an external js file, your page would like

由于看起来您正在使用外部 js 文件,因此您的页面希望

    ... 
    <a href="http://testtesttest.org/" >whatever</a>
    ... 
    <script src="myscriptfile.js"></script>
</body>
</html>

if you're still having problems, you'll have to post a more complete example.

如果您仍然遇到问题,则必须发布更完整的示例。

edits: another point. if you're still having problems, make sure the url you are expecting in the hrefproperty isn't being rewritten. for example, IE will tack a trailing /to the end of a .com url if you don't provide it, which would cause your comparison to fail.

编辑:另一点。如果您仍然遇到问题,请确保您在href属性中期望的 url没有被重写。例如,/如果您不提供,IE 会在 .com url 的末尾添加一个尾随,这会导致您的比较失败。