将关键字搜索结果重定向到网址

问题描述 投票:0回答:1

我正在学习网站建设,html,css,javascript。 我想知道如何将搜索结果重定向到点击事件上的网址。
我有一个简单的本地网站,不是在线的,只是在我的电脑上。 我上面有几页,每页上都有一些说明。 没有连接后端、服务器或数据库。因此搜索仅查看 js 文件中可用的硬编码关键字。

我构建了一个具有自动完成功能的搜索栏。 当我开始在搜索框中输入内容时,可能的匹配项会显示在结果框中。

search result box

结果来自 javascript 文件中的硬编码关键字:

let availableKeywords = [
    'how to learn cooking',
    'hot to filter water',
    'how to make a soup',
    'how to use a mixer',
    'how to make flour',
    'how to write a recipe',
    'how to instal light bulb',
    'how to bake a cookie',
    'how to replace hard drive',
];

搜索框HTML代码:

@*  Search bar area *@
<div class="search-box">
    <div class="row">
        <input type="text" id="input-box" placeholder="Search..." autocomplete="off" />
        <button type="submit"><i class="fa-solid fa-magnifying-glass"></i></button>
    </div>
   
    <div class="result-box">
        @*  this should be populated by script after searching keywords *@
    </div>
</div>

我的JS函数检查输入框并匹配关键字:

inputBox.onkeyup = function () {
    let result = [];
    let input = inputBox.value;
    /*if not zero or null*/
    if (input.length) {
        /* filter will match keywords defined above */
        result = availableKeywords.filter((keyword) => {
            return keyword.toLowerCase().includes(input.toLowerCase());
        });
        /* this is for debugging, it will be displayed in browser-console area */
        console.log(result);
    }
    /* show matches in results box */
    display(result);
    
    if (!result.length) {
        resultsBox.innerHTML = '';
    }
}

/* this will populate drop down box under search field if any matches */
function display(result) {
    const content = result.map((list) => {
        return "<li onclick=selectInput(this)>" + list + "</li>";
    });
    /* insert result list in html page */
    resultsBox.innerHTML = "<ul>" + content.join('') + "</ul>";
}

我希望能够在用户单击搜索结果之一时重定向到特定页面/网址。 例如,如果我点击“如何做汤”,我希望浏览器转到 //..makesoup.html

我不知道该怎么做。 我怀疑我需要创建一个地图或字典,将关键字映射到网址,应该如下所示(我猜): 下面的代码可能有错误的语法,所以我不好。

let keywordsWitUrl = [
    { 'how to learn cooking': "learnCooking.html"},
    { 'hot to filter water': "filterWater.html"},
    { 'how to make a soup': "makeSoup.html"},
    { 'how to use a mixer': "useMixer.html"},
    { 'how to make flour': "makeFlour.html"},
    { 'how to write a recipe': "writeRecipe.html"},
    { 'how to instal light bulb': "instalBulb.html"},
    { 'how to bake a cookie': "bakeCookie.html"},
    { 'how to replace hard drive': "replaceHD.html"}
];

我不知道如何在 javascript 中做到这一点,而且我在网上找不到任何帮助..

如何使搜索仅搜索关键字而不搜索关联的网址? 如何将指令的关键字/全名绑定到网址?

我已经有“单击”事件,现在它只是将指令的全名插入搜索框中,并清除结果框。 当我点击某些搜索结果时,如何将页面更改为正确的网址?

/* click event, display full article name and clear result box */
function selectInput(list) {
    inputBox.value = list.innerHTML;
    resultsBox.innerHTML = '';
}

我什至不知道从哪里开始.. 任何建议都会有所帮助。
谢谢。

javascript html search searchbar
1个回答
0
投票

您可以通过从 const url = keywordsWithUrl[keyword]; 获取关键字来实现此目的;并将此 URL 传递到标签的 href 属性中。如果你想在链接中添加HTTP,只需编辑链接标签即可

// Keywords array
let availableKeywords = [
    'how to learn cooking',
    'hot to filter water',
    'how to make a soup',
    'how to use a mixer',
    'how to make flour',
    'how to write a recipe',
    'how to instal light bulb',
    'how to bake a cookie',
    'how to replace hard drive'
];

// Mapping each keyword to its corresponding URL
const keywordsWithUrl = {
    'how to learn cooking': 'learnCooking.html',
    'hot to filter water': 'filterWater.html',
    'how to make a soup': 'makeSoup.html',
    'how to use a mixer': 'useMixer.html',
    'how to make flour': 'makeFlour.html',
    'how to write a recipe': 'writeRecipe.html',
    'how to instal light bulb': 'instalBulb.html',
    'how to bake a cookie': 'bakeCookie.html',
    'how to replace hard drive': 'replaceHD.html'
};

// Selecting the input box and results box elements
const inputBox = document.getElementById('input-box');
const resultsBox = document.getElementById('resultsBox');

// Function to handle the keyup event and search for matches
inputBox.onkeyup = function () {
    let result = [];
    let input = inputBox.value;
/*if not zero or null*/
    if (input.length) {
        /* filter will match keywords defined above */
        result = availableKeywords.filter((keyword) => {
            return keyword.toLowerCase().includes(input.toLowerCase());
        });
         /* this is for debugging, it will be displayed in browser-console area */
        console.log(result);
    }
    /* show matches in results box */
    display(result);

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

/* this will populate drop down box under search field if any matches */
function display(result) {
    const content = result.map((keyword) => {
        // Get the corresponding URL for each keyword
        const url = keywordsWithUrl[keyword];
        if (url) {
            // Create an <li> with an <a> tag for redirection
            return `<li><a href="${url}">${keyword}</a></li>`;
        } else {
            return `<li>${keyword}</li>`;
        }
    });

   /* insert result list in html page */
    resultsBox.innerHTML = `<ul>${content.join('')}</ul>`;
}
<!-- HTML for the search box -->
<div class="search-box">
    <div class="row">
        <input type="text" id="input-box" placeholder="Search..." autocomplete="off" />
        <button type="submit"><i class="fa-solid fa-magnifying-glass"></i></button>
    </div>
   
    <div class="result-box" id="resultsBox">
        <!-- This will be populated by JavaScript after matching keywords -->
    </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.