在setItem

时间:2018-11-05 02:07:23

标签: javascript local-storage

加载页面时,将调用 init_table 函数,而“ #csv” btn将绑定一个click函数。单击#csv并在localStorage中打印'export2csv'后,它为空,但是有时它可以工作,为什么?

function init_table() {
    var url = 'http://localhost:3000/api/feature/featureInFbpGet?nameInFB=UL PHY';
    localStorage.setItem('export2csv', url);
    console.log(localStorage.getItem('export2csv'));//could print the value   
    table = $('#example').DataTable({
    ajax:{url: url}}).draw();
    //...... some operation
    });
}

$('#csv').click(function(e){
        e.preventDefault();
        console.log('2.export2csv', localStorage.getItem('export2csv'));// here will print null
        var opencsv = window.open('./html/other/feature_statement_csv.html');
        // setTimeout(function(){opencsv.close();}, 5000);
    });

1 个答案:

答案 0 :(得分:-1)

您需要在页面加载时调用init_table函数,只是坐在那里的函数本身不会调用它:)

function init_table() {
    var url = 'http://localhost:3000/api/feature/featureInFbpGet?nameInFB=UL PHY';
    localStorage.setItem('export2csv', url);
    console.log(localStorage.getItem('export2csv'));//could print the value   
    table = $('#example').DataTable({
    ajax:{url: url}}).draw();
    //...... some operation
    });
}
// Call the init_table function when the page loads
init_table();

$('#csv').click(function(e){
        e.preventDefault();
        console.log('2.export2csv', localStorage.getItem('export2csv'));// here will print null
        var opencsv = window.open('./html/other/feature_statement_csv.html');
        // setTimeout(function(){opencsv.close();}, 5000);
    });