开发者

Add target to links as file.js is being read

开发者 https://www.devze.com 2023-02-04 14:07 出处:网络
If I have a recent comments.js file (coming from another server) is there anyway I can add a TARGET=\"_top\" to the links that are in the file.js as the file.js is being read and added to the page?

If I have a recent comments.js file (coming from another server) is there anyway I can add a TARGET="_top" to the links that are in the file.js as the file.js is being read and added to the page?

Reason: it is in an iFrame and unless I can add the target top... when you click on a link it will open the new page inside the iFrame. I need it to of course go to the top of the site.

I can't change the code or add the link targets myself on the original file.js coming from the other server.

It would have to be done as it开发者_StackOverflow社区 is being downloaded.

The site is of course PHP

Thanks


Outside the iframe:

var linkArray = window.frames['frameName'].getElementsByTagName('a');
for (var i=0; i<linkArray.length; i++) {
  linkArray[i].target = '_top';
}

Or inside the iframe:

var linkArray = document.getElementsByTagName('a');
for (var i=0; i<linkArray.length; i++) {
  linkArray[i].target = '_top';
}

You need to wrap either into an event that fires after all links from the external file has loaded.


Using javascript, you can manipulate the DOM of the iframe after loading is finished and add the target attributes:

<html>
    <head>
        <script type="text/javascript">
            function add_targets(iframe) {
                var links = iframe.contentWindow.document.getElementsByTagName('a');
                for(var i=0; i<links.length; i++) {
                    links[i].target = "_TOP";
                }
            }
        </script>
    </head>
    <body>
        <iframe src="links.html" onload="add_targets(this)"></iframe>
    </body>
</html>


window.frames[x].document.getElementsByTagName('a').each(function(item){
    item.setAttribute('target','_top');
})
0

精彩评论

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

关注公众号