查找包含给定子字符串的所有单词

时间:2013-10-08 19:32:20

标签: javascript jquery

我是Javascript的新手,我打算编写一个函数,将一个数组中的所有字符串写入文档,该数组包含当前输入到输入文本字段中的字符串作为子字符串。

<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input type="text" >
    <p></p>
<script>

    var names = ["armadillo", "blue", "com", "demo", "engine"];

    $("input").keypress(function() {
    var incomplete = $( this ).val();

    searchStrings();

    };

    function(searchStrings())
    {
        for(name in names)
        {
            if(name.indexOf(incomplete) != -1)
            {
                document.write(name);
            } else
            {
                document.write("no match found");
            }
        }
    };
});
</script>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

您需要重写searchStrings()函数,因此需要参数:

function searchStrings(incomplete)
{
    for(name in names)
    {
        if(name.indexOf(incomplete) != -1)
        {
            document.write(name);
        } else
        {
            document.write("no match found");
        }
    }
};

你需要这样称呼它:

searchStrings(incomplete);

修复语法错误,您的代码应如下所示:

var names = ["armadillo", "blue", "com", "demo", "engine"];

function searchStrings(incomplete) {
    for (name in names) {
        if (name.indexOf(incomplete) != -1) {
            alert(name);
        } else {
            alert("no match found");
        }
    }
};

$("input").keyup(function () {
    var incomplete = $(this).val();
    searchStrings(incomplete);
});

<强> JSFiddle

答案 1 :(得分:0)

我认为您需要更改此功能(删除额外的括号)

function searchStrings(incomplete)
    {
        for(name in names)
        {
            if(name.indexOf(incomplete) != -1)
            {
                document.write(name);
            } else
            {
                document.write("no match found");
            }
        }
    };

并将其称为

searchStrings(incomplete);

答案 2 :(得分:0)

http://jsfiddle.net/DrekX/

因为你正在使用jQuery,所以使用它是最充分的。

var names = ["armadillo", "blue", "com", "demo", "engine"];

// references to jQuery belong in a wrapper

jQuery(document).ready(function($){

    $("input").keyup(function() {        
        searchStrings(this.value);
    });

    function searchStrings( search_value )
    {
        if(!search_value.length){
            $('#names-found').html('');
            return;
        }

        var names_found = $.map(names, function( value, index ){            
            return ~value.indexOf(search_value) ? value : null;
        });

        $('#names-found').html(
            names_found.length == 0 ? 'No names found.' :
            '<b>Names found:</b> ' + names_found.join(', ')
        )        
    }
});