Мне нужна кнопка закрытия на моих окнах javascript

поэтому я создаю приложение, которое будет регистрировать транзакции от клиентов для кафе, и я работаю над своей страницей текущих заказов, и на них будут поля для представления этих заказов. Я очень некомпетентен в javascript, поэтому я не уверен, как добавить кнопку закрытия в свои ящики, когда человек закончил с заказом. Может ли кто-нибудь помочь мне с этим. Спасибо. Это мой код

#mydiv {
    position: absolute;
    z-index: 9;
    background-color: #f1f1f1;
    text-align: center;
    border: 1px solid #d3d3d3;
}

<div id = "mydiv">
  <div id = "mydivheader">Order Num#</div>
  <p>Order Items</p>
  <span id='close' onclick='this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); return false;'>x</span>
</div>

<div id = "mydiv2">
  <div id = "mydivheader">Order Num#</div>
  <p>Order Items</p>
</div>

<div id = "mydiv3">
  <div id = "mydivheader">Order Num#</div>
  <p>Order Items</p>
</div>

<script>
//Make the DIV element draggagle:
dragElement(document.getElementById("mydiv"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;

  }

Не могли бы вы уточнить проблемную часть кода? Я вижу, что ваш JS много чего делает. Читателям будет полезно сосредоточиться на той части кода, которая связана с вашей проблемой.

Mtxz 04.09.2018 12:34

Спасибо за отзыв, только что отредактировал.

Kinnaz 04.09.2018 12:52
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
2
67
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

onClick принимает функции. Попробуйте создать функцию, чтобы скрыть карточку. Затем вызовите функцию при нажатии кнопки.

С remove это можно было бы сделать проще.

например..

function orderCompleted(event) {
  event.target.parentElement.classList.add('hide-card')
}
.card {
  border: 1px solid #333;
  margin: 5px;
  padding: 5px;
}

.hide-card {
  display: none;
}
<div id = "card-1" class = "card">
  <h3>Order Number: 123</h3>
  <ul>
    <li>Burger</li>
    <li>Diet coke</li>
  </ul>
  <button onclick = "orderCompleted(event)">Completed</button>
</div>

<div id = "card-2" class = "card">
  <h3>Order Number: 124</h3>
  <ul>
    <li>Pizza</li>
    <li>Hot chocolate</li>
  </ul>
  <button onclick = "orderCompleted(event);">Completed</button>
</div>

Выше скроет карту из текущего просмотра. Надеюсь, вы не используете статические данные для заказов (.json). В таком случае каждый раз, когда вы перезагружаете страницу, скрытые карточки будут появляться снова, поскольку мы не обновляем заказ как завершенный. Если вы не видите этого в рамках того, что вы делаете, не обращайте на это внимания.

Ответ принят как подходящий

Я добавил свой код между следующими, я надеюсь, что он выполнит ваше требование

//START UPDATED CODE

//END UPDATED CODE

//Make the DIV element draggagle:
dragElement(document.getElementById("mydiv"));
//START UPDATED CODE
function removeElement(DivId) {
     document.getElementById(DivId).remove();
}
//END UPDATED CODE


function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;

  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

//Make the DIV element draggagle:
dragElement(document.getElementById("mydiv2"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

//Make the DIV element draggagle:
dragElement(document.getElementById("mydiv3"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
#mydiv {
    position: absolute;
    z-index: 9;
    background-color: #f1f1f1;
    text-align: center;
    border: 1px solid #d3d3d3;
}

#mydiv2 {
    position: absolute;
    z-index: 9;
    background-color: #f1f1f1;
    text-align: center;
    border: 1px solid #d3d3d3;
}

#mydiv3 {
    position: absolute;
    z-index: 9;
    background-color: #f1f1f1;
    text-align: center;
    border: 1px solid #d3d3d3;
}
#mydivheader {
    padding: 10px;
    cursor: move;
    z-index: 10;
    background-color: #2196F3;
    color: #fff;
}
<html>
  <head>
  <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
  <!-- START UPDATED CODE -->
  <script  src = "https://code.jquery.com/jquery-3.3.1.min.js" integrity = "sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8 = "  crossorigin = "anonymous"></script>
  <!-- END UPDATED CODE -->
  <link rel = "stylesheet" type = "text/css" href = "css_stylesheet.css">
  </head>
  <body>
<div id = "tabs" ul class = "nav nav-pills">
      <li><a data-toggle = "pill" href = "#current_orders">Current Orders</a></li>
      <li><a data-toggle = "pill" href = "#new_order">New Order</a></li>
      <li><a data-toggle = "pill" href = "#past_orders">Past Orders</a></li>
</div>
<div id = "mydiv" class = "orderBox">
  <div id = "mydivheader">Order Num#</div>
  <p>Order Items</p>
  <!-- START UPDATED CODE -->
  <span id='close' onclick = "removeElement('mydiv')"  style = "cursor: pointer;" >x</span>
  <!-- END UPDATED CODE -->
</div>

<div id = "mydiv2"  class = "orderBox" style = "top: 25px; left: 169px;">
  <div id = "mydivheader">Order Num#</div>
  <p>Order Items</p>
  <!-- START UPDATED CODE -->
  <span id='close' onclick = "removeElement('mydiv2')"  style = "cursor: pointer;">x</span>
  <!-- END UPDATED CODE -->
</div>

<div id = "mydiv3"  class = "orderBox" style = "top: 23px; left: 378px;">
  <div id = "mydivheader">Order Num#</div>
  <p>Order Items</p>
  <!-- START UPDATED CODE -->
  <span id='close' onclick = "removeElement('mydiv3')"  style = "cursor: pointer;" >x</span>
  <!-- END UPDATED CODE -->
</div>
</body>
</html>

Другие вопросы по теме