开发者

Fetch and Replace href attribute value of <a> tag using prototype

I have a simple link inside my tml (apache tapestry specific) :

<a href="www.google.com" class="info-value" target="new">www.google.com</a>

Now on the browser if I am trying to click the link, actually it's redirecting to

http://localhost:8080/..../..../www.google.com

Instead of it should open a new tab for that link.

So the logic which I am thinking is :

1) Fire a javascript on page load
2) Get the href value of anchor tag 
3) Append http:开发者_如何学C// at the start, if it doesn't contains it.

So to do this, actually I want to use prototype (javascript framework), and I am bit new to this...

How can I write the function using the Prototype.js library?


You don't say where the value for your href is coming from. As you say you need to prepend an "http". Assuming the link is dynamically rendered, why don't you just do this server-side, probably much easier. In tml:

... href="${url}" ....

and in .java:

public String getUrl() {
  return "http://" + url;
}

This is a much better approach than doing it client-side as what happens if the user has javascript turned off?

On the other hand, if it's a static link in your .tml, just write "http://www.google.com"!

Edit: In light of your comment below:

public String getUrl() {

   if (!url.startsWith("http://") {
      url = "http://" + url;
   }

   return url;
}

The above is just an example of what do do. You can either add another method to activityDetails which does this (e.g getExternalLinkWithProtocol()), or provide a wrapper method similar to the one above.


No reason to do this on the client side. Simply change your template to:

<a href="http://www.google.com" class="info-value" target="new">www.google.com</a>

and if it's based on a property:

<a href="http://${hostname}" class="info-value" target="new">${hostname}</a>

... adjust to fit your properties, etc.


window.onload = function(){
    var links = document.links;
    for(var i=links.length-1; i>=0; i--){
        var link = links[i];
        var href = link.getAttribute("href");
        if(href.indexOf("http://") < 0){
            link.href = "http://" + href;
        }
    }
};
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜