4
4

4 回答 4

2

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

window.onload = MakeMenuLinksOpenInNewWindow;

或者:

<body onload="MakeMenuLinksOpenInNewWindow();">
于 2010-09-01T20:09:58.767 回答
1

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

$("a[href='http://testtesttest.org/']").attr("target", "_blank");
于 2010-09-01T20:08:59.403 回答
1

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

但如果你必须...

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;
于 2010-09-01T20:27:21.460 回答
0

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

因为看起来您正在使用外部 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 href property 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.

于 2010-09-01T21:18:53.370 回答