jQueryを使って、メモリにデータを保存したり、削除したりする
HTMLのある要素の文字列を取得して、それをメモリ上に保存したいときは、jQueryのdata()関数を使います。
取得したデータをdata()を使って保存したり、removeData()関数を使って破棄したりすることができます。
http://semooh.jp/jquery/api/internals/jQuery.data/elem,+name/
サンプルを見てみましょう。
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>jQueryでデータをremoveする</title> <script src="js/jquery-1.11.1.js"></script> <script> $(document).ready(function() { $('#store-data').click(function() { var targetData = $('#target-data').text(); alert(targetData); $('#store-data').data('mydata',{target: 'パラグラフのデータ', string: targetData}); }); $('#show-data').click(function() { alert('保存したデータは→' + JSON.stringify($('#store-data').data())); }); $('#remove-data').click(function() { $('#store-data').removeData(); }); }); </script> </head> <body> <button id="store-data">データを保存する</button><br> <button id="show-data">データを見せる</button><br> <button id="remove-data">データを削除する</button> <p id="target-data">これは保存したいデータ(文字列の)です。</p> </body> </html>
これを表示すると以下のようになります。