0

I am trying to put all object names in HTML and I am using this function.

  function getExistingLinks() {
      $.post( "http://0.0.0.0:9292/api/links", function( data ) {
        var names = data.map(function (i) {
        return i['link'].name
        });
        document.querySelector(".link-names").innerHTML = names;
      });
    }

html is very simple:

 <form id="addbookmark">
    <p><label for="title">Title</label><br />
    <input type="text" id="title" name="title" size="50" value="" /></p>
    <p><label for="url">Url</label><br />
    <input type="text" id="url" name="url" size="50" value="" /></p>
        <p class="link-names"></p>
    <p><input id="save" type="submit" value="Save Link" /></p>
  </form>

But in this situation all the names ale in one div .link-names, I would prefer put each name in separate div .link-name How can I do this?

4

2 回答 2

2

遍历名称并附加每个名称怎么样?

var container = document.querySelector(".link-names");
names.forEach(function(name) {
    var div = document.createElement('div');
    div.innerHTML = name;
    container.appendChild(div);
    div.setAttribute('class', 'link-name');
});
于 2013-10-21T06:59:50.613 回答
1

利用$.each

 $.post( "http://0.0.0.0:9292/api/links", function( data ) {
   $.each(data,function (i,v) {
        var newDiv=$('<div />',{"class":"linkname",text:v.name});
        $('.link-names').append(newDiv);
        //or
         $('<div />',{"class":"linkname",text:v.name}).appendTo(".link-names");

    });

  }); 
于 2013-10-21T07:00:55.690 回答