如何使用多个哈希

How to use multiple hashes?

本文关键字:哈希 何使用      更新时间:2023-09-26

目前我使用Ben's 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.

现在我需要在那里添加一个值- filter。我认为结果哈希URL可以像

#page1&filter=1-1-0 
#filter=1-1-0 (if page number is omitted)
#page1 (if filter is not defined)

如何解析?即如何理解page是否被定义,如果filter被定义(以及1, 10的值是什么-我分别需要它们)?

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

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

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'}
    }
}

你可以很容易地使它通用。

请,也看看这里:在JavaScript中解析查询字符串-只需将window.location.search.substring(1)更改为哈希。