3

I am trying to take a list of urls and iteratively search for a keyword in the pages that they link to. However, when I run the program, it is returning only the last element of the list the number of links whose pages have the keyword. When I attempt to run it with

http://www.google.com
http://www.yahoo.com
http://www.bing.com

and search for

google

in them, it returns

http://www.bing.com
http://www.bing.com

Why does it take the last element of the list when I set it to each element in the for loop? Below is my code.

<html>
<head>
<title></title>
</head>
<body>
<div>
    Links: <textarea rows="4" cols="50"></textarea><br>
    Search term: <input type="text" name="search" id="search"><br>
    <button>search</button>
</div>
<div id="result">
    <ul>
    </ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function searchLinks() {
    var links = $('textarea').val();
    links = links.replace(/(\r\n|\n|\r)/gm," ");
    links = links.replace("  "," ").split(" ");
    var searchTerm = $("#search").val();
    for(var i=0;i<links.length;i++) {
        var link = links[i];
        $.get(link).success(function(data){
            if (data.indexOf(searchTerm) > -1) {
                $( "#result ul" ).append("<li>"+link+"</li>");
            }
        });
    }
}
var search = $("button");
search.click(function() {searchLinks()});
</script>
</body>
</html>

1 Answers1

3

You need to use a closure when looping over that async call:

for(var i=0;i<links.length;i++) {
    (function(link) {
        $.get(link).success(function(data){
            if (data.indexOf(searchTerm) > -1) {
                $( "#result ul" ).append("<li>"+link+"</li>");
            }
        });
    })(links[i])
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157