2012-08-14 54 views
0

我尝试创建一个jQuery的自我暗示功能(只experimental- jQuery的小白),使用$(EL)。html的功能,呈现出正被服务的数据IM:html jquery函数不适用于keydown事件?

$("#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/ 我似乎不知道会出现什么问题?

+0

什么它应该做,这是不是? – 2012-08-14 17:40:30

+0

它的意思是显示#suggestions,它隐藏在内部,并将数据从questions数组中提取出来,就像自动提示一样。但它没有这样做,我知道问题是在.html函数:) – user1551482 2012-08-14 17:42:08

+0

根据我的经验html()在keydown中工作正常,你肯定你的代码实际上把东西放在.html()? – 2012-08-14 17:44:16

回答

1

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

使用map功能找回的数组物体

+0

你的解决方案是不使用jQuery的'.map()'。它使用本地的。 – 2012-08-14 17:59:10

+0

我的错误。从来没有意识到它是香草 – 2012-08-14 17:59:55

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.
reference

修复下面的代码:

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

demo

0

来自_each的结果未在html中使用。您需要保存和回报生成的字符串:

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