如何保存动态添加的div元素?

时间:2017-11-15 10:24:09

标签: javascript jquery html

此函数动态添加新div:

$(document).ready(function() {
  i = '1';
  x = '0';

  $("#btn3").click(function() {
    i++;
    x++;

    z = x * 2;
    r = z + 1;

    $('<div class="mainContainer"><div class="relayBlock"><span class="relayTitle">Obwód ' + i + ' </span> <button class="btn btn-block btn-lg btn-primary" type="button" id=' + z + ' onClick="relayClick(this.id)">Wł</button> <button class="btn btn-block btn-lg btn-danger" type="button" id=' + r + ' onClick="relayClick(this.id)">Wył</button></div></div>').appendTo("#container");
  });
});

如何保存新创建的&#34; div&#34; ?新的&#34; div&#34;刷新页面后必须可见。

2 个答案:

答案 0 :(得分:0)

您可以使用html保存localStorage内容:

保存

  var html = $('#container').html();
  window.localStorage.setItem('content',html);

<强>读:

$('#container').html(window.localStorage.getItem('content'));

JSFiddle

如果您想要清空localStorage,请执行以下操作:

window.localStorage.removeItem('content');

<强> JSFiddle

答案 1 :(得分:0)

$(document).ready(function() {
  i = '1';
  x = '0';

  $("#btn3").click(function() {
    i++;
    x++;

    z = x * 2;
    r = z + 1;

    $("#container").append('<div class="mainContainer"><div class="relayBlock"><span class="relayTitle">Obwód ' + i + ' </span> <button class="btn btn-block btn-lg btn-primary" type="button" id=' + z + ' onClick="relayClick(this.id)">Wł</button> <button class="btn btn-block btn-lg btn-danger" type="button" id=' + r + ' onClick="relayClick(this.id)">Wył</button></div></div>');
  });
});

需要更改附加元素