【问题标题】:Prevent JQM causing page to scroll to top on form submission防止 JQM 导致页面在表单提交时滚动到顶部
【发布时间】:2021-02-28 00:29:30
【问题描述】:

我正在构建一个底部带有搜索功能的网页。我正在使用 JQuery Mobile 在移动设备上向我的轮播添加触摸导航,但它也会导致页面在提交搜索表单时滚动到顶部。看起来它正在尝试滚动到表单,但在加载 JQuery Mobile 时会滚动回顶部。我想将用户保留在页面底部,或者至少在提交后返回表单。什么是不让用户感到如此不愉快的体验的最佳方式?

下面是表单和它的js。

html -

  <form id="search" method="GET">
    <input type="text" name="search" id="terms" data-role="none">
    <button id="submit" data-role="none" data-ajax="false"></button>
  </form>
  <div id="results">
  ...
  </div>

js-

$(function(){
  var searchParams    = new URLSearchParams(window.location.search),
      results_section = $("#search-results--section"),
      results         = results_section.find(".result"),
      index           = 0,
      input           = $("#terms"),
      availableTerms  = []; // store array to be used for autocomplete
    
    results.each(function(){
      var result    = $(this),
          shortname = result.data("shortname"),
          fullname  = result.data("fullname");
     
      
      if (searchParams.has("search")) {
        var search = searchParams.get("search").toLowerCase();

        if (shortname.indexOf(search) != -1 || fullname.indexOf(search) != -1) {
          result.show();
        } else {
          result.hide();
        }
        // set input's value to search query
        input.val(search);
      }
  });
  ...
});

我使用的是 JQM 1.4.5 版。

【问题讨论】:

标签: jquery jquery-mobile


【解决方案1】:

您似乎需要使用以下内容:

  1. 使用event.preventDefault(); 可防止单击“提交”时页面刷新。
    见:https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
  2. 使用window.location.pathnamehistory.pushState 可以在不刷新页面的情况下更改URL 中的“搜索”参数。
    见:https://developer.mozilla.org/en-US/docs/Web/API/History_API

示例(使用 jquery 3.5.1):

$('#submit').click(function(){
    event.preventDefault();
    url = window.location.pathname + '?searc=' + $('#terms').val();
    history.pushState({page: 1}, "title", url );
    alert(window.location.search);   
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-05
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多