-1

我是 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>
4

3 回答 3

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

于 2013-10-08T19:36:45.630 回答
0

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

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

并称它为

searchStrings(incomplete);
于 2013-10-08T19:36:33.670 回答
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(', ')
        )        
    }
});
于 2013-10-08T19:56:04.330 回答