且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

点击一次只追加一次新元素,并将其保存到本地存储html javascript

更新时间:2022-12-26 18:27:43

Pass this to the onclick function. That way, after you do your things, just remove the listener to click or disable the button.

Also, when the page loads, load the information from the storage, if it's true, directly call the function and then disable the button. Maybe it isn't exaclty what you need, but it can help a lot, you can follow this logic to get there. The code below is just an example.
OBS: it won't work well here because localStorage is not allowed in ***.

In this fiddle you can try it better: https://jsfiddle.net/so5u1c4z/
On the fiddle above, create the element, then save and reload the page. the element will be there once the page loads.

$(document).ready(function(){

 add_prev = function (elem) {
    var NewElement = document.createElement('div');
    NewElement.innerHTML = 'New Element';
    NewElement.id = 'NewElement';
    document.getElementById('Neighbor2').append(NewElement);
   localStorage.setItem('elementCreated', true);
    if (elem){
      $(elem).attr('disabled', true);    
    }
  } 

  var isCreated = localStorage.getItem('elementCreated');
  if (isCreated){
    add_prev();
    $("#btnAdd").attr('disabled', true); 
  }
 
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" onclick="add_prev(this);" value="ACTION" id="btnAdd">
<div id="Neighbor2"></div>

相关阅读

技术问答最新文章