从表单提交更改URL哈希
在我的index.html上,我有以下forms:
哪个正确地重定向到/search?s=searchvalue
但是如何使用javascript将其更改为/search#s=searchvalue
?
不是用jQuery但这应该工作:
另见这个小提琴手: http : //jsfiddle.net/SujwN/
我建议:
$('#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小提琴演示 。
参考文献:
-
attr()
。 -
decodeURIComponent()
。 -
encodeURIComponent()
。 -
event.preventDefault()
。 -
submit()
。 -
val()
。 -
window.location.hash
。