5

我在页面上有一个对象,表示我需要使用要添加以下功能dataTable的 url 跟踪的版本列表/releases

  1. 如果/releases?query=<query>dataTable将使用提供的查询进行初始化
  2. query如果用户更改搜索词,则更新参数
  3. 浏览器中的后退和前进按钮转到相应的查询

到目前为止,我可以做前 2 个,但是当我监听popstate事件时,重绘表格会触发pushState我不知道如何防止的事件。到目前为止,这是我的代码:

$(document).ready(function(){
  var prevSearch;
  var table = $('#releases').dataTable({
    "bJQueryUI" : true,
    "sPaginationType" : "full_numbers",
    "iDisplayLength" : 50,
    "oSearch": {"sSearch": '#{params[:query]}'},
    "fnDrawCallback": function(oSettings) {
        var curSearch = oSettings.oPreviousSearch.sSearch;
        if (!prevSearch) {
          prevSearch = curSearch;
        } else if (curSearch != prevSearch) {
          console.log("changed to: " + curSearch);
          history.pushState({query: curSearch}, "title", "releases?query=" + curSearch);
          prevSearch = curSearch;
        }
     }
  });
  window.addEventListener("popstate", function(e) {
    if (e.state) {
      table.fnFilter(e.state.query);          
    }
  });
});

请注意,我使用的是rails后端,这是页面中提供的内联 javascript。

4

1 回答 1

3

您在这里只有 2 个选项:

  • 将 pushState 代码移出 drawCallback。当用户输入某些内容时,必须有一些其他代码导致数据表绘制。把你的 pushState 代码放在那里。这是理想的解决方案
  • 添加这样的黑客

    $(document).ready(function () {
        var prevSearch;
        var saveState = true;
        var table = $('#releases').dataTable({
            "bJQueryUI":true,
            "sPaginationType":"full_numbers",
            "iDisplayLength":50,
            "oSearch":{"sSearch":'#{params[:query]}'},
            "fnDrawCallback":function (oSettings) {
                var curSearch = oSettings.oPreviousSearch.sSearch;
                if (!prevSearch) {
                    prevSearch = curSearch;
                } else if (curSearch != prevSearch) {
                    console.log("changed to: " + curSearch);
                    if (saveState) {
                        history.pushState({query:curSearch}, "title", "releases?query=" + curSearch);
                    }
                    prevSearch = curSearch;
                }
            }
        });
        window.addEventListener("popstate", function (e) {
            if (e.state) {
                saveState = false;
                table.fnFilter(e.state.query);
                saveState = true;
            }
        });
    });
    
于 2012-11-13T06:25:21.980 回答