简体   繁体   中英

Reload a div with dynamic content using jQuery

The task is to reload a list div with all it's content.

The content is space and foo , which are generated also with javascript.

<div id="list-wrapper">
    <div id="list">
        <div class="space"></div>
        <div class="foo"></div>
        <div class="foo"></div>
        <div class="foo"></div>
        <div class="space"></div>
    </div>
</div>

I'm trying to use

$("#list-wrapper").load(document.URL + " #list");

but that doesn't work properly - the reloaded list is empty:

<div id="list-wrapper">
    <div id="list">
    </div>
</div>

Also I tried

$("#list").load(document.URL + " #list");

Again, the new list is empty.

What's the way to do it?

Edit To make it clear the task. Imagine we manually made some changes on webpage, by opening Chrome Dev Tools and deleted 1 of 3 foo 's. And after that, we want that the script will reload the list div, to show all 3 foo 's, not 2.

$.load will do a HTTP request to the same URL and obtain the markup without any javascript being applied. Since you are saying that #list gets populated by javascript then it will be empty.

From jQuery docs :

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL , however, the scripts are stripped out prior to the DOM being updated, and thus are not executed.

There's an easy way to clone loaded elements .clone .

$('#list').clone().prop('id', '#list-wrapper').appendTo('body');

Just first empty the html of the div and then load the new html everytime.

$("#list").html( ).load(document.

   URL+ "#list");

There is gap in id selector in ur code(Ie #list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM