将innerHTML作为UL返回

时间:2015-07-15 18:34:37

标签: javascript jquery

我将我的对象作为视图中粘在一起的事物列表返回。我想将它们分成一个很好的列表。

我错过了什么?

HTML

 <div id="myPlace">
 </div>

的JavaScript

  for (var i = 0; i < results.length; i++) {
    var place = results[i];
    console.log(place)
    document.getElementById("myPlace").innerHTML += place.name + " - " + place.vicinity 
  }
}

3 个答案:

答案 0 :(得分:4)

可以创建一个字符串并在末尾插入

var htmlStr = '<ul>';
for (var i = 0; i < results.length; i++) {
    var place = results[i];
    htmlStr += '<li>'+ place.name + " - " + place.vicinity +'</li>';
  }
htmlStr += '</ul>';

document.getElementById("myPlace").innerHTML = htmlStr;

答案 1 :(得分:0)

如果我不正确地理解你的问题,请原谅我,但你想在ul-li标签上列出每个项目的名称和附近?如果是这样,你可以这样做。

<div id="myPlace">
</div>

var results = [{"name": "name 1", "vicinity" : "vicinity 1"},
              {"name": "name 2", "vicinity" : "vicinity 2"},
              {"name": "name 3", "vicinity" : "vicinity 2"}];

for (var i = 0; i < results.length; i++) {

    var ul = '<ul>';
    ul += '<li>'+results[i].name+'</li>';
    ul += '<li>'+results[i].vicinity+'</li>';
    ul += '</ul>';
    document.getElementById("myPlace").innerHTML += ul;

  }

Working Fiddle

答案 2 :(得分:0)

如果我理解正确的话:

// Declare list outside the scope of the for loop.
var list = "<ul>";

for (var i = 0; i < results.length; i++) 
{
    var place = results[i];
    console.log(place)
    // Add the <li>name - vicinity</li> text
    list += "<li>" + place.name + " - " + place.vicinity + "</li>"; 
}
// Close the list.
list += "</ul>";
// Insert the new "list" data.
document.getElementById("myPlace").innerHTML += list;