onClick时变量不一致更新

时间:2016-03-01 19:56:39

标签: javascript jquery onclick

我正在尝试创建用于保存用户搜索过滤器的Cookie(如您所见,我们有3个下拉菜单),这样如果他们离开域名,并在最近30分钟内返回,他们将拥有他们的最后搜索过滤器已准备好启动AJAX。以下是下拉列表的代码。

  <span id="category_filter" class="filter-select" data-target="filter_categories" data-curr_filter="communities">
  Communities &nbsp; <i class="fa fa-angle-down"></i>
</span></label>
<label>filter by
  <span id="topic_filter" class="filter-select" data-cat="" data-target="filter_topics" data-curr_filter="affordability" data-curr_filter_id="47">
  Affordability &nbsp; <i class="fa fa-angle-down"></i>
</span></label>
<label>sort by
  <span id="sort_by_filter" class="filter-select" data-target="filter_sort" data-curr_filter="created_at">
  Most recent &nbsp; <i class="fa fa-angle-down"></i>
</span></label>

使用了一个onclick函数('.filter-list&gt; li'),这里有一些代码。它的作用是用选定的列表元素替换下拉列表(例如,分别为买入与租金,邻域,大多数视图),并在下拉列表中更改数据-curr_filter:

(document).on(
    'click',
    '.filter-list > li',
    function() {
      var $text = $(this).text();
      var $val = $(this).data('val');
      var $parent_target = $(this).parent().attr('id');
      var $sortByFilter = null;
      var $topicFilter = null;

      if ($(this).parent('#filter_sort').length) {
        var thissort = $(this).data('val');
        $('.topic-search')
          .find('[data-target="' + $parent_target + '"]')
          .html($text + ' &nbsp; <i class="fa fa-angle-down"></i>')
          .attr('data-curr_filter', $val);
        $sortByFilter = thissort;
      } else {
        $sortByFilter = $('#sort_by_filter').data('curr_filter');
      }

      //cookie business
      var cookieCatFilter = $('#category_filter').data('curr_filter');
      var cookieTopicFilter = $('#topic_filter').data('curr_filter');
      var cookieSortFilter = $('#sort_by_filter').data('curr_filter');
      console.log(cookieCatFilter);
      console.log(cookieTopicFilter);
      console.log(cookieSortFilter);;

      var d = new Date();
      d.setMinutes(d.getMinutes() + 30);
      var expires = "expires=" + d.toUTCString();

      document.cookie = "catFilter=" + cookieCatFilter + "; " + expires + "; path=/";
      document.cookie = "topicFilter=" + cookieTopicFilter + "; " + expires + "; path=/";
      document.cookie = "sortFilter=" + cookieSortFilter + "; " + expires + "; path=/";
      // end of cookie business

然而,正在发生的事情是,通常情况下,控制台日志几乎总是停留在第一个代码片段中的默认过滤器上。更改'#topic_filter'或'#sort_by_filter'后,它会记录前一个'#category_filter'和#topic_filter(总是落后)。更改#sort_by_filter永远不会导致data-curr_filter更新。

有什么想法吗?

0 个答案:

没有答案