如何使用多个哈希值?

LA_*_*LA_ 3 javascript jquery jquery-bbq

目前,我通过 Ben 的 Alman jquery-hashchange 插件在哈希中使用页码:

$(document).ready(function(){
    $(window).hashchange( function(){
      var hash = (location.hash) ? location.hash.slice(1) : 'page1';
      $.ajax({
          url: '/list/' + hash, // result url like page1, page2 etc.
Run Code Online (Sandbox Code Playgroud)

现在我需要添加一个值 - filter。我认为结果哈希 URL 可能看起来像

#page1&filter=1-1-0 
#filter=1-1-0 (if page number is omitted)
#page1 (if filter is not defined)
Run Code Online (Sandbox Code Playgroud)

该如何解析呢?即如何理解是否page已定义,是否filter已定义(以及值是什么 - 110- 我分别需要它们)?

我正在考虑 Ben 的 Alman BBQ 插件,但是 (1) 对于这样简单的任务来说,它看起来太复杂了,(2) 不确定如何使用没有值的参数(page1、page2 等)。

Oro*_*102 5

用于两个硬编码变量的非常简单且不可扩展的解析器:

var hash_parts = location.hash.split('&', 2); //2 - limit, may be changed if more than two arguments

for(i in hash_parts) {
    if(hash_parts[i].indexOf("page") === 0) { //begins with "page"
        var current_page_number = hash_parts[i].substr(4);
    }
    else if(hash_parts[i].indexOf("filter") === 0) { //begins with "filter"
        var filter = hash_parts[i].split('=', 2);
        var filer_values = filter[1].split('-'); //filter_values == {'1', '1', '0'}
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以轻松地使其通用。

请也看看这里:Parse query string in JavaScript - just change window.location.search.substring(1)to hash。