Javascript 将输入与每个id进行比较,并输出最接近的匹配id

Javascript 将输入与每个id进行比较,并输出最接近的匹配id,javascript,jquery,html,Javascript,Jquery,Html,我正在我的网站上进行基本搜索。在搜索中键入时,它会自动将输入与文档中的每个元素id进行比较。当找到匹配项时,它滚动到匹配的元素。到目前为止,仅当您输入准确的id(不包括区分大小写和空格)时,搜索才起作用。 以下是我的JQuery代码: $('#search-box').focus(function() { $('#search-box').keyup(function () { var x = $('#search-box').val().replace(/\s+/g,

我正在我的网站上进行基本搜索。在搜索中键入时,它会自动将输入与文档中的每个元素id进行比较。当找到匹配项时,它滚动到匹配的元素。到目前为止,仅当您输入准确的id(不包括区分大小写和空格)时,搜索才起作用。 以下是我的JQuery代码:

$('#search-box').focus(function() {
    $('#search-box').keyup(function () {
        var x = $('#search-box').val().replace(/\s+/g, '').toLowerCase();
            if ($("#" + x).length !== 0) {
                navbarHeight = $('#fixed-navbar').height();
                $('html, body').animate({scrollTop:$('#'+x).position().top - window.navbarHeight}, 500);
        }
    });
});
我想,从.match()到使用List.js之类的插件,我已经尝试了所有的方法

有没有办法将输入的文本与id进行比较并输出第一个匹配的文本?公差修改器应整洁,但不是必需的。

我的解决方案:
//自动搜索第一个匹配的id
var-idArray=$(“div[id^='x-'])//find-span with-id属性
.map(函数(){return this.id;})//转换为一组id
.get();//转换为数组实例(可选)
导航栏高度=$(“#固定导航栏”).height();
控制台日志(idArray);
$(“#搜索框”).keyup(函数(){

对于(var i=0;我已经尝试了从.match()到使用List.js之类的插件的所有方法。好吧,什么有效或无效?@Mathletics我认为可以很安全地说OP尝试了什么都无效(否则为什么在这里问这个问题?)考虑使用类似的文本()对于您提到的“容差修饰符”。@Greg看起来不错,但我认为javascript也可以做同样的事情。这不是主要问题。通过进一步搜索,我现在认为我必须将每个id为的div添加到一个数组中并从那里开始。这是我最初的计划,但我认为我过于复杂了,就像我通常做的那样。@Elvegirl,我的错误,我错了读得不够仔细@
// Searches automatically for first matching id

var idArray = $("div[id^='x-']")        // find spans with ID attribute
    .map(function() { return this.id; })// convert to set of IDs
    .get();                             // convert to instance of Array (optional)

navbarHeight = $('#fixed-navbar').height();

console.log(idArray);

$('#search-box').keyup(function () {

    for (var i=0; i<idArray.length; i++) {

        var input = $('#search-box').val().replace(/\s+/g, '').toLowerCase();
        matched = idArray[i].match(new RegExp(input));

        if (matched !== null) {
            $('html, body').animate({scrollTop:$('#'+ idArray[i]).position().top - window.navbarHeight});
            console.log('Matched part: ' + matched);
            break;
        };

        if (matched == undefined) {
            matched = [];
            matched.length = 0;
        };
    };
});