You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现本地静态网站搜索结果点击跳转至指定URL

实现搜索结果点击跳转至指定本地页面

1. 重构关键词-URL映射数据结构

把原有的字符串数组改成包含关键词和对应页面路径的对象数组,结构更清晰,便于后续操作:

// 替换原来的availableKeywords数组
const keywordUrlMap = [
    { keyword: 'how to learn cooking', url: 'learnCooking.html' },
    { keyword: 'how to filter water', url: 'filterWater.html' }, // 修正拼写错误"hot"→"how"
    { keyword: 'how to make a soup', url: 'makeSoup.html' },
    { keyword: 'how to use a mixer', url: 'useMixer.html' },
    { keyword: 'how to make flour', url: 'makeFlour.html' },
    { keyword: 'how to write a recipe', url: 'writeRecipe.html' },
    { keyword: 'how to install light bulb', url: 'installBulb.html' }, // 修正拼写"instal"→"install"
    { keyword: 'how to bake a cookie', url: 'bakeCookie.html' },
    { keyword: 'how to replace hard drive', url: 'replaceHD.html' }
];

2. 调整搜索过滤逻辑

修改onkeyup事件的过滤规则,仅针对对象中的keyword字段进行匹配,完全不涉及URL内容:

const inputBox = document.getElementById('input-box');
const resultsBox = document.querySelector('.result-box');

inputBox.onkeyup = function () {
    let results = [];
    const input = inputBox.value.trim().toLowerCase();

    if (input.length) {
        // 仅匹配关键词字段
        results = keywordUrlMap.filter(item => {
            return item.keyword.toLowerCase().includes(input);
        });
        console.log(results);
    }
    display(results);

    if (!results.length) {
        resultsBox.innerHTML = '';
    }
}

3. 修改display函数,存储URL信息

在生成搜索结果列表项时,用data-url属性把页面路径绑定到<li>标签上,方便点击时获取:

function display(results) {
    const content = results.map(item => {
        return `<li data-url="${item.url}" onclick="selectInput(this)">${item.keyword}</li>`;
    });
    resultsBox.innerHTML = `<ul>${content.join('')}</ul>`;
}

4. 更新点击事件,实现页面跳转

修改selectInput函数,获取绑定的URL并跳转,同时保留原有的填充搜索框、清空结果框逻辑:

function selectInput(listItem) {
    // 填充搜索框
    inputBox.value = listItem.innerHTML;
    // 清空结果框
    resultsBox.innerHTML = '';
    // 跳转到目标页面
    const targetUrl = listItem.getAttribute('data-url');
    if (targetUrl) {
        window.location.href = targetUrl;
    }
}

额外优化:搜索按钮的提交逻辑

给页面上的搜索按钮添加点击事件,支持输入关键词后直接点击按钮跳转:

const searchBtn = document.querySelector('.search-box button');
searchBtn.addEventListener('click', function(e) {
    e.preventDefault();
    const inputVal = inputBox.value.trim().toLowerCase();
    if (!inputVal) return;

    // 查找完全匹配的关键词
    const matchedItem = keywordUrlMap.find(item => {
        return item.keyword.toLowerCase() === inputVal;
    });

    if (matchedItem) {
        window.location.href = matchedItem.url;
    } else {
        alert('未找到匹配的页面');
    }
});

内容的提问来源于stack exchange,提问作者mer063

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 11:53:14