首页搜索框传递参数,并在搜索页面中的搜索框中进行显示,搜索框绑定回车键进行搜索

实现搜索条件和搜索内容固定,以及回车键搜索跳转

1.写出搜索条件和搜索框

<form class="parent">
        <select id="searchSelect"  style="border: 1px solid #325da7;border-right: none;" value="resource">
          <option value="resource">资源名称</option>
          <option value="user">作者名称</option>
        </select>
        <input type="text" class="search" placeholder="搜索" id="searchtxt" />
        <input type="button" id="selectBtn" class="btn" />
</form>

2.添加scss样式

.parent {
        margin-top: 10px;
        display: flex;
        flex-wrap: nowrap;

        .search {
          width: 448px;
          height: 36px;
          outline: none;
          border: 1.5px solid #325da7;
        }

        .btn {
          height: 40px;
          width: 60px;
          background: #325da7 url('https://www.ydwenku.com/master/images/searchico.png') center center no-repeat;
          background-size: 35px;
          border: none;
        }
      }

页面
在这里插入图片描述

3.搜索框选择条件,在搜索框中输入内容,然后进行页面跳转

let selectedValue = 'resource';
const searchSelectElement = document.getElementById("searchSelect");  //搜索框条件选择下拉框
const searchInputElement = document.getElementById("searchtxt"); //搜索输入框
const selectBtnElement = document.getElementById("selectBtn"); //搜索按钮
searchSelectElement.addEventListener("change", searchSelect);
searchInputElement.addEventListener("input", handleSearchInput);
searchInputElement.addEventListener("keypress", handleSearchKeyPress);

function handleSearchKeyPress(event) {
  if (event.key === "Enter") {
    event.preventDefault(); // 阻止默认行为
    openSearchPage(searchInputElement.value);
  }
}

function handleSearchInput(event) {
  const searchText = event.target.value;
  selectBtnElement.onclick = function () {
    openSearchPage(searchText);
  };
}
 function openSearchPage(searchText) {
  const url = `/html/searchpage/search.html?searchText=${searchText}&selectSearch=${selectedValue}`;
  window.open(url);
}

在搜索框中输入内容,然后进行页面跳转
在这里插入图片描述

4.页面跳转后从地址栏中获取相关数据,搜索条件和搜索框中的内容

const urlsearch = new URLSearchParams(location.search);
const serchname = urlsearch.get("searchText");  //获取地址栏中传递的参数
const serChange = urlsearch.get("selectSearch");
$('#searchtxt').val(serchname);
$('#searchSelect').val(serChange)

在这里插入图片描述
从地址栏中获取到相关数据searchText和selectSearch的值

$('#searchtxt').val(serchname);  // 搜索框中条件固定
$('#searchSelect').val(serChange) // 搜索框中搜索内容固定

在这里插入图片描述

  • 23
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luanma3p

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值