简体   繁体   中英

Append Div Class with Ajax Loop

I have an Ajax script that reads an XML file and appends each node inside a div with an ID "links." The script is working OK, but I'd like to display each result within a class "col-md-3".

Here's the loop from the Ajax script:

$(xml).find('ref').each(function () {
  // set thumbs and big image paths
  var thumbUrl = 'img/thumbs/';
  var bigUrl = 'img/';

  $('<a />')
  .append($('<img>').prop('src', thumbUrl + img).attr('alt', alt))
  .prop('href', bigUrl + img)
  .prop('title', title)
  .prop('alt', alt)
  .attr('data-gallery', '')
  .appendTo($('#links'));
}); 

The result looks like this:

<div id="links">
  <a href="img/apple.jpg" title="Apple" data-gallery="">
  <img src="img/thumbs/apple.jpg" alt="Apple"></a>

  <a href="img/orange.jpg" title="Orange" data-gallery="">
  <img src="img/thumbs/orange.jpg" alt="Orange"></a>
</div>

I'd like to display each image link inside a column class "col-md-3" like this:

<div id="links">
  <div class="col-md-3">
    <a href="img/apple.jpg" title="Apple" data-gallery="">
    <img src="img/thumbs/apple.jpg" alt="Apple"></a>
  </div>

  <div class="col-md-3">
    <a href="img/orange.jpg" title="Orange" data-gallery="">
    <img src="img/thumbs/orange.jpg" alt="Orange"></a>
  </div>
</div>

Try wrap

$('#links a').wrap('<div class="col-md-3">');

https://jsfiddle.net/xwLmm1d0/1/

I would generate complete HTML code before inserting into DOM. It saves resources, also you can actually see what you insert:

 xml = $.parseXML( '<ref img="350x150" alt="Alt 1" title="Title 1"></ref>' ); var newItemHtml = ''; var thumbUrl = 'https://placehold.it/'; var bigUrl = 'https://placehold.it/'; var links = $('#links'); $(xml).find('ref').each(function(i) { var thisRef = $(this); var src = thumbUrl + thisRef.attr('img'); var href = bigUrl + thisRef.attr('img'); var alt = thisRef.attr('alt'); var title = thisRef.attr('title'); newItemHtml += '<div class="col-md-3">\\n'; newItemHtml += ' <a href="' + href + '" title="' + title + '" data-gallery="">\\n'; newItemHtml += ' <img src="' + src + '" alt="' + alt + '">\\n'; newItemHtml += ' </a>\\n'; newItemHtml += '</div>\\n'; }); links.append(newItemHtml); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="links"></div> 

Also on this Fiddle .

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