开发者

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

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?

function MakeMenuLinksOpenInNewWindow() {
    var links = document.getElementsByTagName("a");
    for (var i = 0; i < l开发者_StackOverflow中文版inks.length; i++) {
        if (links[i].href == "http://testtesttest.org/")
            links[i].target = "_blank";
    }
}
MakeMenuLinksOpenInNewWindow();


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

window.onload = MakeMenuLinksOpenInNewWindow;

or:

<body onload="MakeMenuLinksOpenInNewWindow();">


You should probably not be setting this javascript. And instead use 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;


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

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


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.

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

    ... 
    <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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜