2012-11-24 21 views
3

在我的index.html我有以下形式:改變從一種形式的URL哈希提交

<form action="/search" id="search-form"> 
    <input type="text" id="search-input" name="s" x-webkit-speech> 
</form> 

哪個正確地重定向到/search?s=searchvalue,但我怎麼能使用javascript改變,要/search#s=searchvalue

回答

7

那麼不使用jQuery,但應該工作:

<form action="/search" id="search-form" 
     onsubmit="location.href=this.action+'#s='+this.s.value; return false;"> 
    <input type="text" id="search-input" name="s" x-webkit-speech> 
</form> 

參見本小提琴手:http://jsfiddle.net/SujwN/

4

我建議:

$('#search-form').submit(
    function(e){ 
     e.preventDefault(); 
     var input = $('#search-input'); 
     window.location.hash = input.attr('name') + '=' + encodeURIComponent(input.val()); 
    }); 

以上,再加上on('hashchange', /* other stuff... */)監聽器似乎工作:

$(window).on('hashchange', function(e){ 
    var hash = window.location.hash.substring(1), 
     attrValue = hash.split('='), 
     varName = attrValue[0], 
     varValue = attrValue[1]; 
    console.log(varName, decodeURIComponent(varValue)); 
}); 

JS Fiddle demo

參考文獻:

+0

感謝解決方案和鏈接到您使用的元素,我會牢記在心。我將使用rekire的解決方案,因爲它更簡單,並且需要更少的更改。我已經在我的網站上鍊接了jquery,所以jquery解決方案也得到了應用。 (以防萬一你想知道jQuery標籤)。 – Dlll

0
<form action="/search" id="search-form" onsubmit="document.location = '/search#s=' + $('#search-input').val(); return false;"> 
    <input type="text" id="search-input" name="s" x-webkit-speech> 
</form>