从jquery ajax调用更新html的多个元素 [英] Update multiple elements with html from jquery ajax call

查看:91
本文介绍了从jquery ajax调用更新html的多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个AJAX调用返回需要在页面上替换的多个HTML片段:

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>

目前,我将所有html添加到页面上的隐藏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.

有没有更好的方法(同时仍然返回HTML而不是JSON,因为这是我的控制)?

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

推荐答案

我将创建一个具有所有DOM元素的jQuery对象,并且不会将它们附加到文档中作为隐藏的DIV元素,因为您不需要它。此外,您将不需要在更新后将其删除。

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.

这样的一些:

(假设您的AJAX响应是一个称为数据的变量)

(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);
});

这篇关于从jquery ajax调用更新html的多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆