简体   繁体   中英

Using jQuery to append a div, then append more items into the new div without ID's

I need to use jQuery to append a div with the class 'address-line' to another element with id 'add-results', and then add several elements to the newly created div. Then repeat this for each item of an object.

Here's what I'm trying to end up with:

<div id="add-results">    
  <div class="address-line">
    <h2>title 1</h2>
    <p>desc 1</p>
    <img src="thing1.png" />
  </div>
  <div class="address-line">
    <h2>title 2</h2>
    <p>desc 2</p>
    <img src="thing2.png" />
  </div>
  <!-- etc repeated on a loop -->
</div>

Here's one of the many things I've tried (chdata is the object, chvalue will hold the data):

$.each(chdata, function(name, chvalue) {
  $('#add-results').append('<div class="address-line">');
  $('#add-results').append('<h2>'+chvalue['title']+'</h2>');
  // etc.. adding paragraph, an image, some links.
});

..but of course that results in this:

<div id="add-results">
  <div class="address-line"></div>
  <h2>title 1</h2>
  <p>desc 1</p>
  <img src="thing1.png" />
  <div class="address-line"></div>
  <h2>title 2</h2>
  <p>desc 2</p>
  <img src="thing2.png" />
</div>

I've also tried using:

$('#add-results').append('<div class="address-line">')
.append('<h2>'+chvalue['title']+'</h2>');

..but same result. How can I achieve this?

You could use .appendTo method.

$.each(chdata, function(name, chvalue) {    
  $('<div class="address-line">')
    .append('<h2>'+chvalue['title']+'</h2>')
    // etc.. adding paragraph, an image, some links.
    .appendTo('#add-results'); // at last appendTo the #add-results
});

Store the new div and reference that instead of reusing append. .append is going to return the orignal element you're appending to and not the item that was appended. Try something like this:

var newdiv = $('<div>',{'class':'address-line'});
newdiv.append(...);
$('#add-results').append(newdiv);

Assembled (I prefer leveraging jQuery and the .text method instead of passing raw HTML in case that value contains something that could foul the HTML, but to each his/her own):

$.each(chdata, function(name, chvalue) {
  // Create and store your new div
  var div = $('<div>',{'class':'address-line'});

  // append the new elements to it
  $('<h2>').text(chvalue['title']).appendTo(div);
  $('<p>').text(chvalue['description']).appendTo(div);
  $('<img>',{'src':chvalue['image']}).appendTo(div);

  // insert that new div into #add-results
  div.appendTo('#add-results');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM