简体   繁体   中英

Update multiple elements with html from jquery ajax call

I have an AJAX call which returns multiple HTML fragments that need replacing on the page:

<div data-replace="some-div">
  <p>whatever</p>
</div>

<div data-replace="some-other-div">
  <p>something else</p>
</div>

Currently I am adding all the html to a hidden div on the page and then doing:

    hiddenDiv.find('[data-replace]').each(function () {
        $('#' + $(this).data('replace')).html($(this).html());
        $(this).remove();
    });

which seems to work but seems a bit hacky.

Is there a better way (whilst still returning HTML rather than JSON as this is out of my control)?

I would create a jQuery object with all DOM elements and not append them to the document as an hidden DIV element since you don't need it. Also you won't need to remove it after your update.

Something like this:

(assuming that your AJAX response is a variable called data)

var $data = $("<div>" + data + "</div>");
$data.find('[data-replace]').each(function () {
    $('#' + $(this).data('replace')).html(this.innerHTML);
});

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