2013-10-30 12 views
0

我正在製作一個網頁,以便我可以從自定義頁面搜索谷歌。 但是,當我點擊搜索它確實搜索我的輸入谷歌,但是當我輸入#和%和所有這些字符時,URL應該是不同的。 所以我的問題是我怎麼轉換是這樣的:HTML和JavaScript使搜索輸入準備好了URL

http://www.google.com/#q=Hello World C# 

這樣:

http://www.google.com/#q=HEllo+world+C%23 

使用JavaScript

編輯: 這是我試過的功能使用

$('button#SubmitSearch').click 
    (
     function() 
     { 
      window.location = encodeURIComponent("https://www.google.nl/#q=" + $('input#SearchBar').val()); 
     } 
    ); 

and

$('button#SubmitSearch').click 
    (
     function() 
     { 
      window.location = "https://www.google.nl/#q=" + $('input#SearchBar').val(); 
     } 
    ); 
+0

您需要對搜索文本進行編碼。有一個方便的Javascript函數可以做到這一點,看看'encodeURIComponent' –

回答

1

使用encodeURI,如:

console.log(encodeURI('http://www.google.com/#q=Hello World C#')); 
> "http://www.google.com/#q=Hello%20World%20C#" 

或者 encodeURIComponent

console.log(encodeURIComponent('Hello World C#')); 
> "Hello%20World%20C%23" 

從你OP:

$('button#SubmitSearch').click(function(){ 
    window.location = "https://www.google.nl/#q=" + encodeURIComponent($('input#SearchBar').val()); 
}); 
+0

我甚至沒有提到你的*或*解決方案,因爲它在這種情況下是一種劣勢,因爲你需要追加基本的URL。 – CodingIntrigue

+0

這似乎不工作:( –

+0

檢查更新 – OneOfOne

0

使用功能encodeURIComponent方法:

encodeURIComponent('this is a string with special characters like # and ?') 

希望它能幫助:)

0

試試這個 瓦爾搜索=的document.getElementById( 「搜索框」); 然後使用的addEventListener或的onClick

鍵= key.replace(//g的, 「+」); document.location(「http://google.com/#q」+ search.value);