문제

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 < links.length; i++) {
        if (links[i].href == "http://testtesttest.org/")
            links[i].target = "_blank";
    }
}
MakeMenuLinksOpenInNewWindow();
도움이 되었습니까?

해결책

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

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

다른 팁

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;

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top