Remove HTML Elements from JQuery AJAX load() Respo

2019-06-03 15:39发布

问题:

Is there a possibility to remove specific HTML Elements from a AJAX (load) Response before placing in to the container? In this case I want to remove the "#containerTop", including content, from the response.

Response (HTML):

<html>
  <head></head>
  <body>
    <div id="containerMain">
      <div>...</div>
      <div id="containerTop">Content-to-remove-including-container-div...</div>
    </div>
  </body>
</html>

I've tried this, without success.

<div id="middle"></div>
<script>
$( "#middle" ).load( "http://<URL>",
function(response, status, xhr){
$response.remove('#containerTop');
            });
</script>

Any ideas?

回答1:

.load() inserts the content directly for you. It does not give you an opportunity to modify it before it is inserted. As such you have two options:

  1. You can modify the content after it is inserted, but before it is painted in the .load() completion handler.
  2. You can switch to .get() to get the content as data, then put it into a jQuery object, then modify it using jQuery methods, then insert the modified content into your page yourself.

Here's an example of the second option:

$.get("http://<URL>", function(data) {
    var temp = $(data);
    temp.find('#containerTop').remove();
    $('#middle').empty().append(temp);
});


回答2:

response.find(element).remove()

This works with me