在Javascript中删除eventListener

时间:2016-07-06 15:30:19

标签: javascript javascript-events addeventlistener event-listener

我有以下情况:

标识为section的{​​{1}},双击我正在添加一个包含#sectionlabels和{{1}的表单和inputs

对于点击上的save button按钮,我有另一个事件要删除不想工作的表单。你能告诉我这段代码有什么问题吗?

非常感谢!



close form button

close form

var setAttributes = function setAttributes(el, attrs) {
  for (var key in attrs) {
    el.setAttribute(key, attrs[key]);
  }
};

function createForm() {
  var form = document.createElement('form');
  setAttributes(form, {
    'class': 'hotspot-form'
  });

  var labelT = document.createElement('label');
  setAttributes(labelT, {
    'for': 'title'
  });
  labelT.innerHTML = 'Title';

  var inputT = document.createElement('input');
  setAttributes(inputT, {
    'type': 'text',
    'name': 'title',
    'id': 'inputTitle'
  });

  var labelD = document.createElement('label');
  setAttributes(labelD, {
    'for': 'description'
  });
  labelD.innerHTML = 'Description';

  var inputD = document.createElement('input');
  setAttributes(inputD, {
    'type': 'text',
    'name': 'description',
    'id': 'inputDescription'
  });

  var saveButton = document.createElement('button');
  setAttributes(saveButton, {
    'id': 'button-save',
    'type': 'submit'
  });
  saveButton.innerHTML = 'Save';

  var closeButton = document.createElement('button');
  setAttributes(closeButton, {
    'id': 'button-close',
    'type': 'button'
  });
  closeButton.innerHTML = 'Close Form';

  form.appendChild(labelT);
  form.appendChild(inputT);
  form.appendChild(labelD);
  form.appendChild(inputD);
  form.appendChild(saveButton);
  form.appendChild(closeButton);
  return form;
}
var section = document.querySelector('#section');
console.log(section);
section.addEventListener('dblclick', addForm, false);

function addForm() {
  var form = createForm();

  section.appendChild(form);
  var inputT = form.querySelector('#inputTitle');
  var inputD = form.querySelector('#inputDescription');
  var saveButton = form.querySelector('#button-save');
  var closeButton = form.querySelector('#button-close');

  inputT.addEventListener('input', saveInput, false);
  inputD.addEventListener('input', saveInput, false);

  function saveInput() {
    var newTitle = inputT.value;
    var newDescription = inputD.value;

  }
  closeButton.addEventListener('click', function() {
    section.removeEventListener('dblclick', addForm, false);
  }, false);
}




1 个答案:

答案 0 :(得分:2)

您的关闭按钮事件处理程序不会删除表单,只是从该部分中删除了双击事件处理程序。要删除表单,它应该是:

closeButton.addEventListener("click", function() {
    section.removeChild(form);
});