簡體   English   中英

jQuery / JavaScript:從更改URL哈希 <input> 標簽或表單提交

[英]jQuery / JavaScript: Changing URL hash from <input> tag or on form submit

是否有可能以某種方式影響<input>標記中URL的哈希?

我需要在不刷新頁面的情況下啟動搜索,但是還想更改URL哈希,例如: search.html#query=hello%20world ,當我特別<input> hello world <input>並按下Enter鍵(或提交)時)。

UPD:我有一個AJAX搜索,但是我想保持歷史記錄的前進和后退按鈕有效。

因此,每次用戶搜索內容時,我希望他停留在同一頁面上,通過AJAX加載搜索結果,並更改頁面的URL哈希以啟用歷史記錄按鈕。

使用window.location.hash屬性獲取並設置哈希。

var e = document.getElementById('search');
window.location.hash = "#"+escape(e.value);

是。

document.getElementById('search-form').onsubmit = function() {
    var hash = 'query=' + 
               encodeURIComponent(document.getElementById('query').value);

    window.location.hash = hash;
};

在jsFiddle上看到它

由於您是異步進行的,因此我無法確切告訴您如何執行此操作,但是我假設您具有某種搜索功能,可以在其中獲取input值並執行搜索:

function your_search_function()
{
    var searchString = document.getElementById('your-input').val // get the value

    // do your search stuff...

    window.location.hash = 'query=' + encodeURIComponent(searchString);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM