简体   繁体   中英

the html jquery function is not working on keydown event?

im trying to create an autosuggestion feature in jquery(just experimental- jquery noob), im using the $(el).html function to render out the data that is being served:

$("#suggestions").addClass("active");
     var words = $(this).val();
     var results = searchData(questions,words);
     $("#suggestions").html(function () {
            _.each(results, function(q, key){
                return "<p>" + q.question + "</p>"; // problem is here
            });
        });

the full working code is here: http://jsfiddle.net/HSBWt/6/ i cant seem to know what going wrong?

The problem is your each statement inside html function.

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
reference

Fix the following code:

var suggestions;
_.each(results, function(q, key){
    suggestions += "<p>" + q.question + "</p>";
});
return suggestions;

demo

http://jsfiddle.net/HSBWt/9/

Use the map function to get back an array of the objects

The result from _each is not being used in html . You need to save and return the resulting string:

var results = [];
_.each(results, function(q, key){
  console.log(q.question);
  results.push("<p>" + q.question + "</p>");
});
return results.join('');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM