Explain, please.
How to add an element to the page through .append() , but so that when the page is updated the added element does not disappear?
$('#button').on('click', function(){ $('body').append('<p>test</p>') }); Explain, please.
How to add an element to the page through .append() , but so that when the page is updated the added element does not disappear?
$('#button').on('click', function(){ $('body').append('<p>test</p>') }); Since you have jQuery, the code will be smaller. I agree with the comment about localStorage or DB, but I did not see the answer, so Iβll show the idea with localStorage , in my opinion this approach is simpler. Complement the click method:
$('#button').on('click', function(){ const element = '<p>test</p>'; // ΠΏΠΎΠ»ΠΎΠΆΠΈΠ»ΠΈ Π² ΠΏΠ΅ΡΠ΅ΠΌΠ΅Π½Π½ΡΡ Π½Π°Ρ ΡΠ»Π΅ΠΌΠ΅Π½Ρ $('body').append(element); // Π΄Π°Π±Π°Π²ΠΈΠ»ΠΈ ΠΊ body Π½Π°Ρ ΡΠ»Π΅ΠΌΠ΅Π½Ρ const items = localStorage.getItem('appended'); // ΠΏΠΎΠ»ΡΡΠΈΠ»ΠΈ ΠΏΠΎ ΠΊΠ»ΡΡΡ ΡΠ²ΠΎΠΉ ΡΠ»Π΅ΠΌΠ΅Π½Ρ var elements = JSON.parse(items) || []; // ΡΠ°ΡΠΏΠ°ΡΡΠΈΠ»ΠΈ ΠΏΠΎΠ»ΡΡΠ΅Π½Π½ΡΠΉ ΡΠ»Π΅ΠΌΠ΅Π½Ρ elements.push(element); // Π΄ΠΎΠ±Π°Π²ΠΈΠ»ΠΈ Π² ΠΌΠ°ΡΡΠΈΠ² localStorage.setItem('appended', JSON.stringify(elements)); // Π·Π°ΠΏΠΈΡΠ°Π»ΠΈ Π½ΠΎΠ²ΠΎΠ΅ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ }); And also add a block of code that will add elements after the page has refreshed:
$(document).ready(function() { const items = localStorage.getItem('appended'); // ΠΏΠΎΠ»ΡΡΠΈΠ»ΠΈ ΠΏΠΎ ΠΊΠ»ΡΡΡ ΡΠ²ΠΎΠΉ ΡΠ»Π΅ΠΌΠ΅Π½Ρ var elements = JSON.parse(items) || []; // ΡΠ°ΡΠΏΠ°ΡΡΠΈΠ»ΠΈ ΠΏΠΎΠ»ΡΡΠ΅Π½Π½ΡΠΉ ΡΠ»Π΅ΠΌΠ΅Π½Ρ // ΠΏΡΠΎΠΉΠ΄Π΅ΠΌ ΠΏΠΎ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠ°ΠΌ ΠΈ Π΄ΠΎΠ±Π°Π²ΠΈΠΌ ΠΈΡ
ΠΊ body for (var index = 0; index < elements.length; index++) { $('body').append(elements[index]); // Π΄Π°Π±Π°Π²ΠΈΠ»ΠΈ ΠΊ body Π½Π°Ρ ΡΠ»Π΅ΠΌΠ΅Π½Ρ } }); Useful links:
Use cookies
Static solution: Initially hide this block for the time being, and then show it on click? In the client's cookies, it is necessary to register that this block is already visible and show it immediately upon repeated display.
Dynamic solution: In the form in which this is done, you can use cookies to save which blocks are shown, and which are hidden, and when you refresh the page, after reading the cookie, you can dynamically add / delete the corresponding blocks.
Source: https://ru.stackoverflow.com/questions/919778/
All Articles