最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - location.href to a link without http: - Stack Overflow

programmeradmin3浏览0评论

I have a webpage - / - where I have a button. On click of the button I need to go to a particular link (www.google). The button is like :

<input type="button"
       onclick="javascript:location.href='www.google'"
       value="Click" />

But this button opens a page ".google" which is wrong URL.

I have tried window.location, document.location, document.location.href, location.href but all in vain.

The URL in my onclick can not be restricted to begin with 'http://'.

I have a webpage - http://www.example./ - where I have a button. On click of the button I need to go to a particular link (www.google.). The button is like :

<input type="button"
       onclick="javascript:location.href='www.google.'"
       value="Click" />

But this button opens a page "http://www.example./www.google." which is wrong URL.

I have tried window.location, document.location, document.location.href, location.href but all in vain.

The URL in my onclick can not be restricted to begin with 'http://'.

Share Improve this question edited Aug 31, 2012 at 11:23 CharlesB 90.4k29 gold badges201 silver badges228 bronze badges asked Aug 31, 2012 at 11:16 Riju MahnaRiju Mahna 6,92613 gold badges57 silver badges94 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

You can use the "current" protocol by prefixing your URLs with //

prefixing http:// before url may solve your issue.

if (!url.match(/^http?:\/\//i) || !url.match(/^https?:\/\//i)) {
        url = 'http://' + url;
    }

check this and this for more information.

Since you did not include a protocol (such as for example http), your browser will interpret www.google. as a link to http://www.example./www.google., since you are currently on http://www.example.. Add whatever protocol you want to the href-string, but if you are referring to somewhere else than on the site itself, you must have the protocol.

发布评论

评论列表(0)

  1. 暂无评论