Как редактировать элемент массива с помощью JavaScript

Просто получите экземпляр AppWidgetManager и обновите его напрямую. Или, если вы используете IntentService для выполнения обновлений, вызовите startService() на IntentService. AppWidgetProvider - это способ обновления виджета приложения, но это не единственный способ.

0
задан Shiba Tatsuya 4 March 2019 в 09:24
поделиться

1 ответ

Ниже приведены несколько указаний на то, где вам могут потребоваться корректировки для достижения того, чего вы хотите.

  1. В настоящее время вы добавляете новых слушателей в модал каждый раз, когда нажимаете кнопку редактирования для задачи. Вероятно, это должно быть установлено только один раз. В качестве альтернативы вы должны удалить слушателей, когда модал закрыт.

  2. Ваша функция editModal фактически не открывает модал. Он добавляет слушателя к кнопке # modal-btn, которая затем открывает модал при следующем нажатии кнопки.

  3. Вы устанавливаете идентификаторы как для внешнего div, так и для кнопки редактирования, но идентификаторы не основаны на чем-либо связанном с элементом todo, который вы создаете. Таким образом, все эти элементы имеют одинаковый идентификатор. Идентификатор (сокращение от идентификатора) обычно считается уникальным. Для группировки нескольких элементов вместо этого следует использовать атрибут класса.

  4. Ваша функция "editTodo" вызывает сама. Повторяется до бесконечности. Остерегайтесь повторного использования имен функций.

С учетом сказанного, приведенный ниже код является грубым способом сделать то, что, я думаю, вы хотите сделать, основываясь на предоставленных вами фрагментах:

// Open
const openModal = function() {
  document.querySelector("#my-modal").style.display = "block";
}


  // Close
const closeModal = function() {
  document.querySelector("#my-modal").style.display = "none";
}

function initModal() {
  const modal = document.querySelector("#my-modal");
  const closeBtn = document.querySelector(".close");

  // Events
  closeBtn.addEventListener("click", closeModal);
  window.addEventListener("click", outsideClick);


  // Close If Outside Click
  function outsideClick(e) {
    if (e.target == modal) {
      modal.style.display = "none";
    }
  }
}

const filters = []; // dummy variable

// Generate the DOM structure for a todo
var todos = []
function generateTodoDOM(todo) {
  todos.push(todo);
  const todoEl = document.createElement("div");
  const checkbox = document.createElement("input");
  const label = document.createElement("label");
  checkbox.appendChild(label);
  todoEl.setAttribute("id", "my-todos-" + todo.id);
  const textEl = document.createElement("p");
  const editButton = document.createElement("button");
  editButton.setAttribute("id", "modal-btn-" + todo.id);
  const removeButton = document.createElement("button");
  const createDate = document.createElement("p");
  createDate.textContent = 'Created: ' + new Date();
  createDate.style.color = "#956E93";

  // Setup the todo text
  textEl.textContent = todo.text;
  todoEl.appendChild(textEl);

  // Setup the remove button
  removeButton.textContent = "x";
  todoEl.appendChild(removeButton);
  removeButton.addEventListener("click", function() {
    removeTodo(todo.id);
    saveTodos(todos);
    renderTodos(todos, filters);
  });

  // TODO: Setup the edit note button
  editButton.textContent = "Edit Todo";
  todoEl.appendChild(editButton);
  editButton.addEventListener("click", function() {
    //Launch the modal
    editModal(todo.id);
    openModal();
  });
  // Setup todo checkbox
  checkbox.setAttribute("type", "checkbox");
  checkbox.checked = todo.completed;
  todoEl.appendChild(checkbox);
  checkbox.addEventListener("change", function() {
    toggleTodo(todo.id);
    saveTodos(todos);
    renderTodos(todos, filters);
  });

  todoEl.appendChild(createDate);

  return todoEl;
};


var editFn
//Edit modal todo by id
const editModal = function(id) {
  const todoIndex = todos.findIndex(function(todo) {
    return todo.id === id;
  });
  if (todoIndex > -1) {
    const modal = document.querySelector("#my-modal");
    const editElm = document.querySelector("#editTodo");
    const editTodoContentBtn = document.querySelector("#submitEditTodo")

    editElm.value = todos[todoIndex].text;

    // Events
    editTodoContentBtn.removeEventListener("click", editFn)

    //Edit the content of the textarea
    editFn = function(e) {
      editTodo(id)
      closeModal()
    }

    editTodoContentBtn.addEventListener("click", editFn)

  }
};


//Edit todo by id
const editTodo = function(id) {
  const editTodoContent = document.querySelector('#editTodo')
  const todoIndex = todos.findIndex(function(todo) {
    return todo.id === id;
  });

  if (todoIndex > -1) {
    todos[todoIndex].text = editTodoContent.value;
    saveTodos(todos)
    renderTodos(todos, filters);
  }
};

const saveTodos = function(todos) {
  // dummy method, we're keeping it in memory for this example
}

const renderTodos = function(todosToRender) {
  todos = []; // clear current in-memory array
  var todoList = document.getElementById("todo-container");
  while (todoList.firstChild) {
      todoList.removeChild(todoList.firstChild);
  }
  for(var i = 0; i < todosToRender.length; i++) {
    todoList.appendChild(generateTodoDOM(todosToRender[i]));
  }
};


initModal();
const container = document.getElementById("todo-container");
var generatedTodos = [];
for(var i = 0; i < 10; i++) {
  var todo = { text: "Todo " + (i+1), id: "todo-" + i, completed: false};
  generatedTodos.push(todo);
}
renderTodos(generatedTodos);
/*
Edit todo modal start
*/

:root {
  --modal-duration: 1s;
  --modal-color: #BB8AB8;
}

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  margin: 10% auto;
  width: 35%;
  box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
  animation-name: modalopen;
  animation-duration: var(--modal-duration);
}

.editTextArea{
  width:100%
}

.modal-header h2,
.modal-footer h3 {
  margin: 0;
}

.modal-header {
  background: var(--modal-color);
  padding: 15px;
  color: #fff;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}

.modal-body {
  padding: 10px 20px;
  background: #fff;
}

.modal-footer {
  background: var(--modal-color);
  padding: 10px;
  color: #fff;
  text-align: center;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
}

.close {
  color: #ccc;
  float: right;
  font-size: 30px;
  color: #fff;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}

@keyframes modalopen {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/*
Edit todo modal end
*/
<!DOCTYPE html>
<html>
<head>
	<link rel="stylesheet" href="style.css">
</head>
<body>
	<div id="todo-container">

	</div>
	<!-- Edit modal -->
  <div id="my-modal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <span class="close">&times;</span>
        <h2>Edit Todo</h2>
      </div>
      <div class="modal-body">
        <textarea name="" class="editTextArea" id="editTodo"  rows="10"></textarea>
        <button class="button" id="submitEditTodo">Edit Todo</button>
      </div>
      <div class="modal-footer">
        <!-- <h3>Modal Footer</h3> -->
      </div>
    </div>
   </div>
   <!-- End modal --> 
</body>
</html>

0
ответ дан Silwing 4 March 2019 в 09:24
поделиться
Другие вопросы по тегам:

Похожие вопросы: