将一条消息返回循环jquery

时间:2013-10-30 19:42:11

标签: jquery html for-loop conditional

好吧,我创建了一个简单的搜索器,但是当单词不存在时我需要返回一条消息,但是第一个单词工作正常,但是当我写下最后一个单词时,循环立即中断,如何浏览所有单词并发送一个一个警报没有打破循环?

提前致谢

    <html>
<head>
    <title>buscador</title>
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
</head>

<script type="text/javascript">
$(function(){

/*iniciando el buscador*/
$("#buscar").click(function(){
    var dato =$("#palabra").val().toLowerCase();
    var myArray = [ "hello", "world","apple","bread","milk","pencil"];

        for ( var i = 0; i < myArray.length; i = i + 1 ){
            var flag = false;
                if(dato==myArray[i])
                {
                    alert("exist");
                    return false;
                }

                else if(dato!=myArray[i]){
                 flag=true;
                }
                if(flag) {alert("no exist"); return false;}

            }/*end foreach*/


});
});

</script>

<body>

<form method="post" action="" id="form-search">
<input type="text" id="palabra" name="palabra" placeholder="buscar"/>
<button id="buscar" name="buscar">Buscar</button>

</form>
</body>
</html> 

2 个答案:

答案 0 :(得分:0)

尝试使用$ .inArray(value,array)

如果值不在数组

中,则返回-1

答案 1 :(得分:0)

最简单的,我建议:

$('#buscar').click(function(e){
    e.preventDefault();
    var needle = $('#palabra').val().toLowerCase(),
        haystack = ['hello','world','apple','milk','bread','pencil'],
        found = haystack.indexOf(needle) == -1 ? 'Not found' : 'Found';
    console.log(found);
});

JS Fiddle demo

或者,如果您的浏览器不支持Array.indexOf(),则可以使用上述for循环:

$('#buscar').click(function(e){
    e.preventDefault();
    var needle = $('#palabra').val().toLowerCase(),
        haystack = ['hello','world','apple','milk','bread','pencil'],
        found = false;
    for (var i = 0, len = haystack.length; i < len; i++){
        if (haystack[i] === needle){
            found = true;
        }
    }
    console.log(found ? 'Found' : 'Not found');
});

JS Fiddle demo