jquery ajax加载某个div

Yov*_*ovo 13 html ajax jquery

我的问题很简单,我如何用jquery ajax命令检索某些div

$.ajax({
      url: "test.html",
      success: function(){
           $(this).addClass("done");
      }
  });
Run Code Online (Sandbox Code Playgroud)

喜欢加载

$('#targetDiv').load('http://localhost/test.html #sourceDiv');
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 21

如果div是AJAX响应的一部分:

$.ajax({
    url: 'test.html',
    dataType: 'html',
    success: function(html) {
        var div = $('#sourceDiv', $(html)).addClass('done');
        $('#targetDiv').html(div);
    }
});
Run Code Online (Sandbox Code Playgroud)


Nic*_*tes 7

这是一个略有不同的看法.此外,您的目标div可能默认隐藏,因此我添加了淡入淡出效果以显示它.如果您的html将要更改,那么您可能希望添加缓存:false.

$.ajax({
  url: "html.htm",
  type: "GET",
  dataType: "html",
  success: function (res) {
       $("#targetDiv").html($(res).find("#sourceDiv")
                                  .addClass('done'))
                     .fadeIn('slow');
  }
});
Run Code Online (Sandbox Code Playgroud)

如果您有兴趣,可以查看jQuery如何在这里使用jQuery Source Viewer进行加载