输入和输出用于简单的关键字搜索

时间:2014-02-10 17:25:55

标签: javascript jquery

我是Javascript和Jquery场景的新手。我正在尝试创建一个关键字搜索,当单击一个按钮时,文本框中的短语将在文本区域中给出一个特定的答案。我创建了两个包含我想要的关键字的数组,但我不知道如何让程序查找关键字并回答问题。

这是HTML

<div id="AskAQuestion">

    <div id="questionsArea">
        <div class="questionAreaSpacing"><input type="text" name="questionTxt" id="questionTxt"></div>
        <textarea readonly id="answerArea">

        </textarea>

        <div class="questionAreaSpacing"><input type="submit" name="answerBtn" id="answerBtn" value="Click Me!"></div>
    </div>
</div>

以及脚本:

<script>
var quesArr = ["redcom","google", "orange"];
var ansArr = ["test 1","test 2","test 3"];

function getAnswer(){ 
}; 


function answer(){
    if ($("#questionTxt").val().toLowerCase().string. == getAnswer()){
        $('#answerArea').html("");
    }
    else if($("#questionTxt").val() !=  getAnswer()){
        $('#answerArea').html('You didn\'t say the magic word');
    }
    else if($("#questionTxt").val() == "" ){
        $('#answerArea').html('what are you thinking');
    }
}; 

$("#answerBtn").click(function(){
    answer();
});


$("#questionTxt").keyup(function(e){
    if(e.keyCode == 13){
        $("#answerBtn").click();
    }
});

</script>

请帮助我,我想学习如何做到这一点:(

1 个答案:

答案 0 :(得分:0)

您可以通过将问题作为参数传递给函数来实现此目的。然后遍历quesArr以查看其是否存在并打印出相应的答案:

var quesArr = ["redcom","google", "orange"];
var ansArr = ["test 1","test 2","test 3"];

function getAnswer(question){ 
    var questionIsPresent = false;

    //loop through array to see if question is present
    for (var i = 0; i < quesArr.length; i++) {
        if(quesArr[i] === question){
              $('#answerArea').html(ansArr[i]); 
              questionIsPresent = true;
        }
    }

    if(questionIsPresent == false){
        $('#answerArea').html('You didn\'t say the magic word');
    }

    if(question == "" ){
        $('#answerArea').html('what are you thinking');
    }
}; 

 $("#answerBtn").click(function(){
    //pass in the question to the function
    getAnswer($("#questionTxt").val().toLowerCase());
 });

$("#questionTxt").keyup(function(e){
    if(e.keyCode == 13){
        $("#answerBtn").click();
    }
});

FIDDLE