开发者

Convert location.href URL to Anchor link

Exists any JavaScript or Objective-C method to convert a location.hre开发者_C百科f="MyURL" to <a href="MyURL"></a>??

I have over 200 location.href URL not working with UIWebViewNavigationTypeLinkClicked :-S

Thanks to everyone can help me!


    <a href="http://www.myurl.com" id="myAnchor"></a>

    <script type="text/javascript">
        document.getElementById("myAnchor").setAttribute("href", window.location.href);
        var loc = document.getElementById("myAnchor").getAttribute("href");
        var t = document.createTextNode(loc);
        document.getElementById("myAnchor").appendChild(t);
    </script>

Here is one way of doing it: document.getElementById() grabs a reference to the ID attribute of your anchor(s). The second argument of setAttribute(), "window.location.href" grabs a reference to the url in the current window and sets the href attibute in your anchor to this, however if you have a bunch of location.href()s declared in your code, then store these as a variable before the first line instead and then reference that variable at around the same line as where I have declared "loc". The variable "loc" declares a variable which stores a reference to the newly created href attribute you just declared in the previous line. Then I am declaring a variable "t" which creates a text node in the DOM, with the href from the previous line as the value this variable will hold. Lastly, I use document.getElementById to get "myAnchor" again and append the text node from the previous line to it. So now we can actually see the url in the link.

        //Also, use a for loop to run this action 200 times and correct all of the   hrefs       on your page.
        <script type="text/javascript">
           for (var i=0;i<200;i++){
              //run document.getElementById() and .setAttribute, .createTextNode, etc. here
            }
        </script>

Working fiddle: http://jsfiddle.net/1so33q4z/36/

I would not recommend using document.write(); as mentioned in the other person's post, as this causes the page to work in a way the DOM is not meant to (writes serialized text). Especially if you need to correct 200 of them. See this post Why is document.write considered a "bad practice"?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜