Extract part of HTML document in jQuery

前端 未结 5 1630
囚心锁ツ
囚心锁ツ 2020-11-28 09:01

I want to make an AJAX call to an HTML-returning page, extract part of the HTML (using jQuery selectors), and then use that part in my jQuery-based JavaScript.

The A

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 09:58

    You can use your standard selector syntax, and pass in the data as the context for the selector. The second parameter, data in this case, is our context.

    $.post("getstuff.php", function(data){
      var mainDiv = $("#mainDiv", data); // finds 
    ...
    }, "html");

    This is equivalent to doing:

    $(data).find("#mainDiv");
    

    Depending on how you're planning on using this, $.load() may be a better route to take, as it allows both a URL and a selector to filter the resulting data, which is passed directly into the element the method was called on:

    $("#mylocaldiv").load("getstuff.php #mainDiv");
    

    This would load the contents of

    ...
    in getstuff.php into our local page element
    ...
    .

提交回复
热议问题