繁体   English   中英

../path 不是重定向页面

[英]../path is not redirecting page

我正在尝试将页面转到search.html 根据它是什么页面,search.html 要么位于同一目录中,要么位于上面的目录中。 我不明白为什么它没有重定向。

这是 HTML 代码:

  <form  class="search" onsubmit="searchSite()">
    <input id="search" title="Seach this site" type="text" name="search"
      placeholder="Search this site..">
  </form>

这是JS代码:

function searchSite() {
  var search = document.getElementById("search").value.toLowerCase().split(" ");
  searchArticles(search);
  displayResults();
}

function displayResults() {
  if (window.location.href.indexOf("humans") !== -1 
      || window.location.href.indexOf("other")){ 
    window.location.href = "../search.html";
    console.log(window.location.href);}
  else
    window.location.href = "search.html";
}

搜索之前的网址是: file:///C:Desktop/comp266/unit5/public_html/other/other.html

搜索后网址为: file:///C:Desktop/comp266/unit5/public_html/other/other.html ?search=good

但我希望 URL 为: file:///C:Desktop/comp266/unit5/public_html/search.html

这是因为表单有其默认行为,如您所见,将站点重定向到表单的操作 URL 或带有查询参数的查询 URL。
您可以通过在提交侦听器上返回 false 来防止此默认行为:

  <form  class="search" onsubmit="return searchSite()"> <!-- ADD THIS -->
    <input id="search" title="Seach this site" type="text" name="search"
      placeholder="Search this site..">
  </form>
function searchSite() {
  var search = document.getElementById("search").value.toLowerCase().split(" ");
  searchArticles(search);
  displayResults();

  // ADD THIS
  return false;
}

更正确的方法是做preventDefault以防在 return false 之前可能发生错误:

<form  class="search" onsubmit="return searchSite(event)"> <!-- ADD THIS -->
    <input id="search" title="Seach this site" type="text" name="search"
      placeholder="Search this site..">
  </form>
function searchSite(event) {
  // ADD THIS
  event.preventDefault();

  var search = document.getElementById("search").value.toLowerCase().split(" ");
  searchArticles(search);
  displayResults();

  // ADD THIS
  return false;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM