0

我试图在 jquery 中创建一个自动建议功能(只是实验性的 jquery noob),我使用 $(el).html 函数来呈现正在提供的数据:

$("#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
            });
        });

完整的工作代码在这里:http: //jsfiddle.net/HSBWt/6/ 我似乎不知道出了什么问题?

4

3 回答 3

3

问题是你在函数each内部的声明html

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.
参考

修复以下代码:

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

演示

于 2012-08-14T17:44:07.830 回答
1

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

使用该map函数取回对象数组

于 2012-08-14T17:45:15.140 回答
0

结果 from_each未用于html. 您需要保存并返回结果字符串:

var results = [];
_.each(results, function(q, key){
  console.log(q.question);
  results.push("<p>" + q.question + "</p>");
});
return results.join('');
于 2012-08-14T17:47:17.423 回答