I have a web application that is based on the users creating certain divs through a click function. When the user adds a div I also give them the ability of deleting said function. Each time the user adds a div it is pushed into an array. Then user can save the array and load it when they come back.

The function to delete a div is nested within the function to add as that is the only way I have found make the function work.

The problem I have is that I must also call the delete function within the load function to make delete button work before the add button is clicked. I tried just calling function out side either function but since there are no divs to begin with. So when the page loads and the delete button is clicked, it is implemented twice and ruins the application.

I am new to programming and what I am doing right now is mostly procedural, so any input work be appreciated. I feel like I am making a rookie mistake, the pseudo code is below.

$(button).cick(function(){
    store div in array;
    add div to container;
    call remove function;
});
function loadPage() {
    retrieve stored array;
    add stored divs to container;
    call remove function;
}
loadPage();
有帮助吗?

解决方案

You can delegate the delete action to the container, like this :

$('#container').on('click', '.delete', function() {
    $(this).closest('div.className').remove();
    //here delete stored clone from array.
});

Adjust the selectors to fit your HTML

That way, any button with class="delete", when clicked, will cause its (inner) containing div to be removed (deleted).

  • The action will apply to all delete buttons within the container, regardless of whether they are in place at the time this click handler is attached, or inserted later.
  • This delegated action will remain in place providing the (outer) container itself is not removed (deleted).

其他提示

I think its easier if you have separate buttons to do the adding and deleting. That way you can bind one button to adding the div to the container, and the other to remove the last pushed div.

Something like this may help

  var listOfAddedDivs = [];

  $('.addDivButton').click(addNewDiv);

  $('.removeDivButton').click(removeCurrentDiv);


  function addNewDiv() {
     listOfAddedDivs.push('<div> something </div>');
     updateContainer(listOfAddedDivs);
  }

  function removeCurrentDiv() {
    if(listOfAddedDivs.length >0) {
          listOfAddedDivs.pop();
      }
      updateContainer(listOfAddedDivs);
  }

  function updateContainer(arrayContainingDivs) {

   $('.container').html(arrayContainingDivs.join(' '));
  }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top