Javascript通过单击按钮删除div

时间:2022-10-07 13:16:35

I am trying to dynamically add and remove divs from a page. The divs have inner divs. I have the add functionality working and I can get the first div created to delete. My problem is that I have modified the remove div functionality and I believe it is just a syntax problem that is stopping this from working. Any pointers?

我试图动态添加和删除页面中的div。 div有内在的div。我有添加功能,我可以创建第一个删除div。我的问题是我修改了删除div功能,我相信它只是一个语法问题,正在阻止它工作。有什么指针吗?

This code adds the divs I want and is working:

这段代码添加了我想要的div并且正在工作:

<!--This appends all elements necessary to complete a new step. The divs are nested within the answer_step div here -->
    $("button.add_answer_step_button").click(function () {
        $new_step = $("div.answer_steps").append($('<div id = answer_step_' + answer_identifier_number + ' class = "answer_step">').append($('<div class="answer_step_equation" contenteditable="true" placeholder="Enter The Next Solution Step This Question">')).append($('<div class = "answer_step_description" contenteditable="true" placeholder="Enter A Description as to how this step was reached or how to solve the next step">')).append($('<button class = "remove_answer_step_button">- Remove This Step</button>')));

        <!--Increase identifier number by 1-->
        answer_identifier_number++;
    });

This next code is meant to remove any div for which the remove step button is pressed. I can getting it working for the first one with a bit of code change but I believe that the code below should work for them all. I'm stuck here:

下一个代码用于删除按下删除步骤按钮的任何div。我可以通过一些代码更改让它为第一个工作,但我相信下面的代码应该适用于所有。我被困在这里:

$("#remove_answer_step_button").click(function () {
        $(this).parent().remove();
    });

I have a fiddle created for this here https://jsfiddle.net/max_m/5r07utj1/

我为此创建了一个小提琴https://jsfiddle.net/max_m/5r07utj1/

The functionality to add a new div with inner divs works locally for me but not in the fiddle.

添加带有内部div的新div的功能对我来说是本地的,但不适合小提琴。

Anyway, to my main question - I can get the remove div to work for the first div that is added but not subsequent divs that are added to the page. I think it is only a syntax problem as I have taken this code from someone else here.

无论如何,对于我的主要问题 - 我可以让删除div用于添加的第一个div,但不是后续添加到页面的div。我认为这只是一个语法问题,因为我从这里的其他人那里获取了这些代码。

A solution was found:

找到了一个解决方案:

    $(document).on('click','.remove_answer_step_button', function () {
        $(this).parent().remove();
    });

1 个解决方案

#1


0  

Here's a full working example of what you are trying to accomplish (i think). Its based on your code but it includes ko bindings. There is actually a much shorter way of doing it (html wise) but i didn't want to confuse you too much.

这是一个完整的例子,说明你想要完成的事情(我认为)。它基于您的代码,但它包含ko绑定。实际上有一个更短的方式(明智的html),但我不想太多地混淆你。

I don't know why the code snippet gives an error, it runs fine on the fiddle.

我不知道为什么代码片段会出错,它在小提琴上运行正常。

https://jsfiddle.net/RachGal/na38tmog/

answer_identifier_number = 0;

$(document).on('click', '.add_answer_step_button', function() {
  $new_step = $("#answer_steps").append($('<div id="answer_step' + answer_identifier_number + '" class = "answer_step draggable" data-bind="draggable:true,droppable:true">').append($('<div id="answer_step_equation' + answer_identifier_number + '" class="answer_step_equation" contenteditable="true" placeholder="Enter The Next Solution Step This Question">')).append($('<div id="answer_step_description' + answer_identifier_number + '" class = "answer_step_description" contenteditable="true" placeholder="Enter A Description as to how this step was reached or how to solve the next step">')).append($('<div class="buttons"><button class = "remove_answer_step_button">- Remove This Step</button><button class = "add_answer_step_button">+Add Next Step</button></div>')));

  answer_identifier_number++;
});
var no_children = $('.answer_step_equation').length;

if (no_children == 1) {
  $('.remove_answer_step_button').attr('disabled', true);
  $('.remove_answer_step_button').css("visibility", "hidden");
}

$(document).on('click', '.remove_answer_step_button', function() {
  $(this).parent().parent().remove();
});

var draggableArguments = {
  revert: 'invalid',
  helper: 'clone',
  appendTo: '#answer_steps',
  refreshPositions: true,
  containment: 'parent',
  zIndex: 1500,
  addClasses: false
};

$('#answer_steps').sortable();


var count = 0;
var selectedDraggable;

ko.bindingHandlers.draggable = {
  init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
    $(element).draggable();
    var list = valueAccessor();
    $(element).sortable({
      update: function(event, ui) {
        //retrieve our actual data item
        var answer_step = ko.dataFor(ui.answer_step.get(0));
        //figure out its new position
        var position = ko.utils.arrayIndexOf(ui.answer_step.parent().children(), ui.answer_step[0]);
        //remove the item and add it back in the right spot
        if (position >= 0) {
          list.remove(answer_step);
          list.splice(position, 0, answer_step);
        }
        ui.answer_step.remove();
      }
    });
    $(element).on('click', function() {
      selectedDraggable = $(this);
    });
  }
};

var vm = function() {
  var self = this;
  self.answer_steps = ko.observableArray();
  self.answer_step = ko.observable('');
  self.init = function() {
    self.answer_steps([]);
  };
  self.remove = function(answer_step) {
    self.answer_steps.remove(answer_step);
  };
  self.addNew = function() {
    self.answer_steps.push(self.answer_step());
    self.answer_step('');
  };
  self.init();
};

ko.applyBindings(new vm());
#answer_steps {
  display: block;
  margin-top: 40px;
  width: 100%;
}
.answer_step {
  display: block;
  position: relative;
  width: 98%;
  height: 200px;
}
.draggable {
  border: solid 1px gray;
}
#buttons {
  width: 98%;
  display: block;
}
.answer_step_equation {
  float: left;
  border: 1px solid black;
  background-color: #F0F4F5;
  width: 60%;
  height: 150px;
  margin-top: 20px;
  margin-bottom: 5px;
  text-align: left;
  overflow-x: hidden;
  overflow-y: auto;
}
.answer_step_description {
  float: right;
  border: 1px solid black;
  background-color: #F0F4F5;
  width: 38%;
  height: 150px;
  margin-top: 20px;
  margin-bottom: 5px;
  text-align: justify;
  overflow-x: hidden;
  overflow-y: auto;
}
[contenteditable=true]:empty:not(:focus):before {
  content: attr(placeholder);
  color: #96ADB5;
  text-align: justify;
  font-size: 14pt;
  font-style: italic;
  display: block;
}
button.add_answer_step_button {
  float: right!important;
  width: 200px;
  height: 25px;
  font-size: 12pt;
  font-weight: bold;
  border-radius: 5px;
  background-color: #eee;
  color: #444;
  border: solid 1px gray;
}
button.remove_answer_step_button {
  display: block;
  visibility: visible;
  float: left;
  width: 200px;
  height: 25px;
  font-size: 12pt;
  font-weight: bold;
  border-radius: 5px;
  background-color: #eee;
  color: #444;
  border: solid 1px gray;
}
button.add_answer_step_button:active,
button.add_answer_step_button:hover,
button.remove_answer_step_button:active,
button.remove_answer_step_button:hover {
  background-color: #CDEDF7;
  border: 1px solid blue;
  cursor: pointer;
}
<!doctype html>
<html>
<head>
<link href="https://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="center_column" id="center_column">
  <!--Put in the Plus Sign, Equation and text instruction to allow the user to add a new Div to write the solution and directions-->
  <div id="answer_steps" class="answer_steps" data-bind="foreach:answer_steps">

    <!--Div contains each answer step-->
    <div id="answer_step" class="answer_step draggable" data-bind="draggable:true,droppable:true">
      <!--This placeholder text will empty the div once the user starts typing-->
      <div id="answer_step_equation" class="answer_step_equation" contenteditable="true" placeholder="Enter The Next Solution Step This Question"></div>
      <div id="answer_step_description" class="answer_step_description" contenteditable="true" placeholder="Enter A Description as to how this step was reached or how to solve the next step"></div>
      <!-- Buttons to dynamically add and remove answer divs. The remove functionality is added in JQuery for the add button-->
      <div class="buttons">
        <button class="add_answer_step_button">+ Add next Step</button>
        <button class="remove_answer_step_button">- Remove This Step</button>
      </div>
    </div>
  </div>
</div>
  </body>
  </html>

#1


0  

Here's a full working example of what you are trying to accomplish (i think). Its based on your code but it includes ko bindings. There is actually a much shorter way of doing it (html wise) but i didn't want to confuse you too much.

这是一个完整的例子,说明你想要完成的事情(我认为)。它基于您的代码,但它包含ko绑定。实际上有一个更短的方式(明智的html),但我不想太多地混淆你。

I don't know why the code snippet gives an error, it runs fine on the fiddle.

我不知道为什么代码片段会出错,它在小提琴上运行正常。

https://jsfiddle.net/RachGal/na38tmog/

answer_identifier_number = 0;

$(document).on('click', '.add_answer_step_button', function() {
  $new_step = $("#answer_steps").append($('<div id="answer_step' + answer_identifier_number + '" class = "answer_step draggable" data-bind="draggable:true,droppable:true">').append($('<div id="answer_step_equation' + answer_identifier_number + '" class="answer_step_equation" contenteditable="true" placeholder="Enter The Next Solution Step This Question">')).append($('<div id="answer_step_description' + answer_identifier_number + '" class = "answer_step_description" contenteditable="true" placeholder="Enter A Description as to how this step was reached or how to solve the next step">')).append($('<div class="buttons"><button class = "remove_answer_step_button">- Remove This Step</button><button class = "add_answer_step_button">+Add Next Step</button></div>')));

  answer_identifier_number++;
});
var no_children = $('.answer_step_equation').length;

if (no_children == 1) {
  $('.remove_answer_step_button').attr('disabled', true);
  $('.remove_answer_step_button').css("visibility", "hidden");
}

$(document).on('click', '.remove_answer_step_button', function() {
  $(this).parent().parent().remove();
});

var draggableArguments = {
  revert: 'invalid',
  helper: 'clone',
  appendTo: '#answer_steps',
  refreshPositions: true,
  containment: 'parent',
  zIndex: 1500,
  addClasses: false
};

$('#answer_steps').sortable();


var count = 0;
var selectedDraggable;

ko.bindingHandlers.draggable = {
  init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
    $(element).draggable();
    var list = valueAccessor();
    $(element).sortable({
      update: function(event, ui) {
        //retrieve our actual data item
        var answer_step = ko.dataFor(ui.answer_step.get(0));
        //figure out its new position
        var position = ko.utils.arrayIndexOf(ui.answer_step.parent().children(), ui.answer_step[0]);
        //remove the item and add it back in the right spot
        if (position >= 0) {
          list.remove(answer_step);
          list.splice(position, 0, answer_step);
        }
        ui.answer_step.remove();
      }
    });
    $(element).on('click', function() {
      selectedDraggable = $(this);
    });
  }
};

var vm = function() {
  var self = this;
  self.answer_steps = ko.observableArray();
  self.answer_step = ko.observable('');
  self.init = function() {
    self.answer_steps([]);
  };
  self.remove = function(answer_step) {
    self.answer_steps.remove(answer_step);
  };
  self.addNew = function() {
    self.answer_steps.push(self.answer_step());
    self.answer_step('');
  };
  self.init();
};

ko.applyBindings(new vm());
#answer_steps {
  display: block;
  margin-top: 40px;
  width: 100%;
}
.answer_step {
  display: block;
  position: relative;
  width: 98%;
  height: 200px;
}
.draggable {
  border: solid 1px gray;
}
#buttons {
  width: 98%;
  display: block;
}
.answer_step_equation {
  float: left;
  border: 1px solid black;
  background-color: #F0F4F5;
  width: 60%;
  height: 150px;
  margin-top: 20px;
  margin-bottom: 5px;
  text-align: left;
  overflow-x: hidden;
  overflow-y: auto;
}
.answer_step_description {
  float: right;
  border: 1px solid black;
  background-color: #F0F4F5;
  width: 38%;
  height: 150px;
  margin-top: 20px;
  margin-bottom: 5px;
  text-align: justify;
  overflow-x: hidden;
  overflow-y: auto;
}
[contenteditable=true]:empty:not(:focus):before {
  content: attr(placeholder);
  color: #96ADB5;
  text-align: justify;
  font-size: 14pt;
  font-style: italic;
  display: block;
}
button.add_answer_step_button {
  float: right!important;
  width: 200px;
  height: 25px;
  font-size: 12pt;
  font-weight: bold;
  border-radius: 5px;
  background-color: #eee;
  color: #444;
  border: solid 1px gray;
}
button.remove_answer_step_button {
  display: block;
  visibility: visible;
  float: left;
  width: 200px;
  height: 25px;
  font-size: 12pt;
  font-weight: bold;
  border-radius: 5px;
  background-color: #eee;
  color: #444;
  border: solid 1px gray;
}
button.add_answer_step_button:active,
button.add_answer_step_button:hover,
button.remove_answer_step_button:active,
button.remove_answer_step_button:hover {
  background-color: #CDEDF7;
  border: 1px solid blue;
  cursor: pointer;
}
<!doctype html>
<html>
<head>
<link href="https://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="center_column" id="center_column">
  <!--Put in the Plus Sign, Equation and text instruction to allow the user to add a new Div to write the solution and directions-->
  <div id="answer_steps" class="answer_steps" data-bind="foreach:answer_steps">

    <!--Div contains each answer step-->
    <div id="answer_step" class="answer_step draggable" data-bind="draggable:true,droppable:true">
      <!--This placeholder text will empty the div once the user starts typing-->
      <div id="answer_step_equation" class="answer_step_equation" contenteditable="true" placeholder="Enter The Next Solution Step This Question"></div>
      <div id="answer_step_description" class="answer_step_description" contenteditable="true" placeholder="Enter A Description as to how this step was reached or how to solve the next step"></div>
      <!-- Buttons to dynamically add and remove answer divs. The remove functionality is added in JQuery for the add button-->
      <div class="buttons">
        <button class="add_answer_step_button">+ Add next Step</button>
        <button class="remove_answer_step_button">- Remove This Step</button>
      </div>
    </div>
  </div>
</div>
  </body>
  </html>