【问题标题】:Json loop and appending results to htmlJson循环并将结果附加到html
【发布时间】:2014-11-12 19:32:39
【问题描述】:

我的 JavaScript 循环有问题,因为我使用 keyup 函数我不能使用 html() 函数,因为它只添加最后一个结果,并且附加它会使结果加倍。
如何解决这个问题?

for (var i = 0; i < msg.length; i++)
{
    $('#result').html(' ' + msg[i].info + '</br> ');                               
}

【问题讨论】:

  • #result 是输入字段吗?
  • 结果是 div

标签: javascript jquery loops for-loop


【解决方案1】:

使用上面显示的当前代码,您可以为msg 的每个数组元素删除#result 的内容。 如果要显示每个数组元素,则需要附加结果。如果你按你说的那样得到双倍,那么你的脚本返回结果有问题。

正确的做法是:

$('#result').html(''); //If you want to empty the container before posting results to it
for(var i=0; i<msg.length; i++) {
    $('#result').append(' ' + msg[i].info + '</br> ');
}

【讨论】:

    猜你喜欢
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多