【问题标题】:Javascript removing a div by clicking on a button通过单击按钮删除 div 的 Javascript
【发布时间】:2016-09-15 15:16:44
【问题描述】:

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

此代码添加了我想要的 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++;
    });

接下来的代码旨在删除任何按下删除步骤按钮的 div。我可以通过一些代码更改使其适用于第一个,但我相信下面的代码应该适用于所有人。我被困在这里:

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

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

使用内部 div 添加新 div 的功能对我来说在本地工作,但在小提琴中不起作用。

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

找到了解决办法:

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

【问题讨论】:

  • 一个元素的id 应该是一个unique 字符串(它应该只在DOM 中出现一次)。此外,此'&lt;div id="answer_step class = "answer_step"&gt;' 无效。俯视非唯一id,应该是:'&lt;div id="answer_step" class="answer_step"&gt;'(需要结束引号)。
  • 任何时候你引用的东西在页面上有多个实例,你应该通过类名来引用它(而不是上面评论中提到的 ID)。
  • 您使用的是什么版本的 jQuery? .live() 在 1.9 中被删除,取而代之的是 .on(),其语法相似但不同。
  • 感谢 noahnu、jmoerdyk、乔纳森·格雷。我的部分复制/粘贴错误,因为缺少“ - 在 Fiddle 及更高版本中修复。我将跟进您的建议并修复此代码。.live,我在这里找到并切换到它。不是确定它做了什么,但我正在看的小提琴可以使用它,所以我想我会看看它是否对我有用。

标签: javascript jquery html css dynamic


【解决方案1】:

这是您尝试完成的工作的完整示例(我认为)。它基于您的代码,但包含 ko 绑定。实际上有一种更短的方法(html 明智),但我不想让你太困惑。

我不知道为什么代码 sn-p 会出错,它在小提琴上运行良好。

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>

【讨论】:

    猜你喜欢
    • 2018-01-20
    • 1970-01-01
    • 2011-04-29
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 2013-01-20
    相关资源
    最近更新 更多