Jquery/javascript, filtering html object from ajax response

后端 未结 3 1662
不思量自难忘°
不思量自难忘° 2021-01-03 08:14

I have this piece of html:

Text for div 2
相关标签:
3条回答
  • 2021-01-03 08:37

    If you don't need any special functionality given by the full $.ajax method, you should give $.load() a try:

    The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

    $('#result').load('ajax/test.html #container');
    

    http://api.jquery.com/load/#loading-page-fragments

    0 讨论(0)
  • 2021-01-03 08:50

    You should store it this way:

    $.ajax({
       url: "htmlsnippet.html",
       cache: false,
       async: false,
       dataType: "html",
       success: function(data){
          html = data;
       }
    }
    

    EDIT: Your way of obtaining html works, but it's not recommended.
    You can't grab your last element because you're using filter instead of find, so you should have:

    var htmlFiltered = $(html).find("#1 .text");
    

    instead of

    var htmlFiltered = $(html).filter("#1 .text");
    

    Also W3C recommends not to have numeric IDs.

    EDIT 2: This should work:

    var htmlFiltered = $(html).filter("#1").find(".text");
    

    Hope this helps. Cheers

    0 讨论(0)
  • 2021-01-03 08:59

    This works for me :

    $.get(url,function(content) {
        var content = $(content).find('div.contentWrapper').html();
        ...
    }
    
    0 讨论(0)
提交回复
热议问题