内容加载后将 div 的内容保存在本地存储中

Save content of a div in localstorage after content loads

我通过 ajax 在名为 records 的 div 中加载了一个页面,我想在加载到 div 之后将记录的内容保存到本地存储中div。对于我当前的脚本,它所做的是在加载内容出现之前已经保存了 div 的空内容。

$(document).ready(function() {
    $('#records').load('records.php');
    localStorage.setItem('records', $records.html());   
});

jQuery.load 将回调函数作为其第二个参数。来自文档:

If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed.

加载完成时调用该函数。您只需要将存储代码放入该回调即可。

$(document).ready(function() {
    $('#records').load('records.php', function() {
        localStorage.setItem('records', $records.html());
    });
});