2014-04-05 126 views
0

我正在构建一个程序,该程序允许我搜索文档以查看单词在该文档中出现的次数。我想通过在我创建的搜索框中输入所需的单词来选择要搜索哪个单词。目前,如果我对我正在搜索的单词进行硬编码,它将搜索文档并告诉我它出现的次数。如果我尝试使用搜索框输入一个单词,我总是得到0的结果。我需要一种方法来检索从搜索框中输入的单词并将该单词用作我想要检查的单词。从搜索框中检索文本

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8" /> 
    <title>WordBubble</title> 
    <link rel="stylesheet" type="text/css" href="wordbubble.css"> 
    <script type="text/javascript" src="jquery-1.10.2.js"></script> 
</head> 
<body> 
    <div id="search"> 
    Search Word: <input type="search" name="Wordsearch" size="35"> 
    <button type="submit" class ="searchme">Search</button> 
    </div> 
<script type="text/javascript"> 
    $(document).ready(function(){ 
    $(".searchme").click(function(){ 
     var myWord = $ (this).text(); 
     findDuplicates(); 
    }); 
    }); 

    // ajax call to get comments document 
    function findDuplicates (myWord) { 
    $.get("comm.txt", function(text) { 


     words = text.split(' '), 
     sortedWords = words.slice(0).sort(), 
     duplicateWords = [] 



    for (var i=0; i<sortedWords.length-1; i++) { 
     if (myWord == sortedWords[i]) { 
      duplicateWords.push(sortedWords[i]); 
     } 
    } 

    $("p").html(duplicateWords.length); 
    }); 
} 
</script> 

<p></p> 
</body> 
</html> 

回答

1

在您的点击处理程序中,您从按钮而不是输入中检索搜索字符串。

$(document).ready(function(){ 
    $(".searchme").click(function(){ 
    // get the word from the input 
    var myWord = $('input').val(); 
    findDuplicates(myWord); 
    }); 
});