需要帮助以使用纯JavaScript动态删除项目

发布于 2025-02-02 13:23:39 字数 2702 浏览 2 评论 0原文

要求:

  1. 单击'+添加stop '。

  2. 如果单击删除( x )按钮,则应删除相应的文本框, stop#(序列编号)也应更改。

需要帮助:

我试图达到上述要求。我获得了#1的结果。但是对于#2,添加了更多项目后,删除按钮仅处理/删除最后一个添加的项目,但对于所有项目都应该使用相同的功能。

删除项目后,应保持#序列号。我还需要此逻辑的帮助。

html:

    <form action="https://www.example.com" method="POST">
        <label for="stype">Service Type:</label>
        <select id="stype" name="service-type">
            <option disabled="disabled" selected="selected">Choose Service</option>
            <option value="From Airport">From Airport</option>
            <option value="To Airport">To Airport</option>
        </select><br/><br/>

        <label for="fullname">Name: </label><input id="fullname" name="name" size="20" type="text" maxlength="20" placeholder="John Doe" required /><br/><br/>
        <label for="phone">Phone: </label><input id="phone" name="phone" maxlength="12" type="tel" placeholder="012-345-6789" required /><br/><br/>
        <label for="email">Email: </label><input id="email" name="email" size="30" type="email" maxlength="30" placeholder="[email protected]" required /><br/><br/>

        <label for="ptime">Pickup time </label><input id="ptime" name="pickup-time" type="time" required /><br/><br/>
        <label for="pdate">Pickup Date </label><input id="pdate" name="pickup-date" type="date" required /><br/><br/>
        <div id="add_stop_here">
            
        </div>
        <input type="button" id="add" value="+Add Stop" onclick="test();" />
    </form>

javaScript:

var counter = 0;
function test () {
    counter += 1;
    var addHtml = '\
    <div class="input-box">\
        <label for="stop'+counter+'">Stop '+counter+':</label>\
        <input type="text" id="stop'+counter+'" name="stop"/ >&nbsp;&nbsp;<a id="rmv'+counter+'" class="remove_stop" href="#">x</a>\
    </div>';

    var add_hre = document.getElementById("add_stop_here");
    add_hre.innerHTML += addHtml;

document.querySelector("#rmv"+counter)
.addEventListener('click', function(){
  var removeEl = this.parentNode;
  add_hre.removeChild(removeEl);
});
}

Requirements:

  1. A new text box should appear with a delete button at closing after clicking '+Add Stop'.

  2. If a delete(x) button is clicked, the respective text box should be removed and Stop #(sequence numbering) should be changed as well.

Need help on:

I have tried to achieve the both above requirements. I get results for #1. But for #2, After adding more items, the delete button works/removes only the last added item only but it should work the same for all items.

Stop # sequence number should be maintained after the removal of an item(s). I need help with this logic also.

HTML:

    <form action="https://www.example.com" method="POST">
        <label for="stype">Service Type:</label>
        <select id="stype" name="service-type">
            <option disabled="disabled" selected="selected">Choose Service</option>
            <option value="From Airport">From Airport</option>
            <option value="To Airport">To Airport</option>
        </select><br/><br/>

        <label for="fullname">Name: </label><input id="fullname" name="name" size="20" type="text" maxlength="20" placeholder="John Doe" required /><br/><br/>
        <label for="phone">Phone: </label><input id="phone" name="phone" maxlength="12" type="tel" placeholder="012-345-6789" required /><br/><br/>
        <label for="email">Email: </label><input id="email" name="email" size="30" type="email" maxlength="30" placeholder="[email protected]" required /><br/><br/>

        <label for="ptime">Pickup time </label><input id="ptime" name="pickup-time" type="time" required /><br/><br/>
        <label for="pdate">Pickup Date </label><input id="pdate" name="pickup-date" type="date" required /><br/><br/>
        <div id="add_stop_here">
            
        </div>
        <input type="button" id="add" value="+Add Stop" onclick="test();" />
    </form>

JavaScript:

var counter = 0;
function test () {
    counter += 1;
    var addHtml = '\
    <div class="input-box">\
        <label for="stop'+counter+'">Stop '+counter+':</label>\
        <input type="text" id="stop'+counter+'" name="stop"/ >  <a id="rmv'+counter+'" class="remove_stop" href="#">x</a>\
    </div>';

    var add_hre = document.getElementById("add_stop_here");
    add_hre.innerHTML += addHtml;

document.querySelector("#rmv"+counter)
.addEventListener('click', function(){
  var removeEl = this.parentNode;
  add_hre.removeChild(removeEl);
});
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

彻夜缠绵 2025-02-09 13:23:39

一些要处理的问题:

  • 为了完成这项工作,我会避免使用具有顺序数字的id属性。这不是最好的练习。

    相反,为了将标签元素与其input元素链接起来,制作input element e element a的孩子标签元素。现在,不再需要 和<代码>属性> 不再需要

  • 不要使用innerhtml +=,因为这将重置文档中已经存在的输入的值,并将删除事件侦听器。而是使用insertadjacenthtml

  • 要保持编号的速度,请使用span仅具有该数字的元素,并在每次更改后重新编号所有这些跨度元素。您也可以在插入后使用它,只是为了保持代码清洁,并避免您需要维护计数器。

  • 为避免您需要为每个新元素附加一个新事件处理程序,请在 container 元素上收听单击事件,然后在单个处理程序中检查哪个元素被单击。这称为事件委托

  • 不要命名您的功能测试。给它一个有用的名称,例如insertbusstop

  • 而不是通过HTML属性绑定该处理程序,而是通过代码绑定。

  • 对于多行字符串,您可以使用tick tick定界符(模板文字)

  • 我建议,单击“添加”按钮后,将重点放在新创建的input元素上。这促进了用户的输入过程。

这将是如何工作的:

var add_hre = document.getElementById("add_stop_here");
document.getElementById("add").addEventListener("click", addBusStop);

function addBusStop() {
    var addHtml = `
    <div class="input-box">
        <label>
        Stop <span class="stop_number"></span>
        <input type="text" name="stop"/>  <a class="remove_stop" href="#">x</a>
        </label>
    </div>`;
    add_hre.insertAdjacentHTML("beforeend", addHtml);
    renumber();
    add_hre.querySelector(".input-box:last-child input").focus();
}

function renumber() {
    let i = 1;
    for (let labelSpan of add_hre.querySelectorAll(".stop_number")) {
        labelSpan.textContent = i++;
    }
}

// Use event delegation
add_hre.addEventListener('click', function(e) {
    if (!e.target.classList.contains("remove_stop")) return;
    var removeEl = e.target.parentNode.parentNode;  // need one more level now
    add_hre.removeChild(removeEl);
    renumber();
});
<div id="add_stop_here"></div>
<input type="button" id="add" value="+Add Stop"/>

Some issues to take care of:

  • To make this work, I would refrain from using id attributes that have a sequential number. It is not best practice.

    Instead, in order to link a label element with its input element, make the input element a child of the corresponding label element. Now the id and for attributes are no longer needed.

  • Don't use innerHTML += as that will reset the values of the inputs that are already in the document, and will remove the event listeners. Instead use insertAdjacentHTML.

  • To keep the numbering in pace, use a span element that only has that number, and renumber all those span elements after every change. You can also use it after an insert, just to keep the code clean, and avoid that you need to maintain a counter.

  • To avoid that you need to attach a new event handler for every new element, listen to click events on the container element, and then check in that single handler which element was clicked. This is called event delegation.

  • Don't name your function test. Give it a useful name, like insertBusStop.

  • Instead of binding that handler via HTML attribute, bind it via code.

  • For multi-line strings you can use back tick delimiters (template literals)

  • I'd suggest that after clicking the Add button, the focus is put on the newly created input element. This facilitates the input procedure for the user.

Here is how that would work:

var add_hre = document.getElementById("add_stop_here");
document.getElementById("add").addEventListener("click", addBusStop);

function addBusStop() {
    var addHtml = `
    <div class="input-box">
        <label>
        Stop <span class="stop_number"></span>
        <input type="text" name="stop"/>  <a class="remove_stop" href="#">x</a>
        </label>
    </div>`;
    add_hre.insertAdjacentHTML("beforeend", addHtml);
    renumber();
    add_hre.querySelector(".input-box:last-child input").focus();
}

function renumber() {
    let i = 1;
    for (let labelSpan of add_hre.querySelectorAll(".stop_number")) {
        labelSpan.textContent = i++;
    }
}

// Use event delegation
add_hre.addEventListener('click', function(e) {
    if (!e.target.classList.contains("remove_stop")) return;
    var removeEl = e.target.parentNode.parentNode;  // need one more level now
    add_hre.removeChild(removeEl);
    renumber();
});
<div id="add_stop_here"></div>
<input type="button" id="add" value="+Add Stop"/>

甜警司 2025-02-09 13:23:39

您可以使用每个()find()轻松函数来执行此操作。

var counter = 0;

$("#add").click(function () {
  counter++;
  $("#add_stop_here").append(
    '<div class="input-box"><label for="stop' +
      counter +
      '">Stop' +
      counter +
      ': <input type="text" id="stop' +
      counter +
      '" name="stop"/ ></label>  <a id="rmv' +
      counter +
      '" class="remove_stop" href="#">X</a></div>'
  );
});

$(document).on("click", ".remove_stop", function () {
  $(this).closest("div").remove(); //use closest here
  $("#add_stop_here .input-box").each(function (index) {
    $(this)
      .find("label:eq(0)")
      .attr("id", "stop" + (index + 1));

    $(this)
      .find("label:eq(0)")
      .html("Stop" + (index + 1) + '<input type="text" name="stop" />');
  });
  counter--;
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<form action="https://www.example.com" method="POST">
  <label for="stype">Service Type:</label>
  <select id="stype" name="service-type">
    <option disabled="disabled" selected="selected">Choose Service</option>
    <option value="From Airport">From Airport</option>
    <option value="To Airport">To Airport</option></select
  ><br /><br />

  <label for="fullname">Name: </label
  ><input
    id="fullname"
    name="name"
    size="20"
    type="text"
    maxlength="20"
    placeholder="John Doe"
    required
  /><br /><br />
  <label for="phone">Phone: </label
  ><input
    id="phone"
    name="phone"
    maxlength="12"
    type="tel"
    placeholder="012-345-6789"
    required
  /><br /><br />
  <label for="email">Email: </label
  ><input
    id="email"
    name="email"
    size="30"
    type="email"
    maxlength="30"
    placeholder="[email protected]"
    required
  /><br /><br />

  <label for="ptime">Pickup time </label
  ><input id="ptime" name="pickup-time" type="time" required /><br /><br />
  <label for="pdate">Pickup Date </label
  ><input id="pdate" name="pickup-date" type="date" required /><br /><br />
  <div id="add_stop_here"></div>
  <input type="button" id="add" value="+Add Stop" />
</form>

You can do this with each() and find() function easily.

var counter = 0;

$("#add").click(function () {
  counter++;
  $("#add_stop_here").append(
    '<div class="input-box"><label for="stop' +
      counter +
      '">Stop' +
      counter +
      ': <input type="text" id="stop' +
      counter +
      '" name="stop"/ ></label>  <a id="rmv' +
      counter +
      '" class="remove_stop" href="#">X</a></div>'
  );
});

$(document).on("click", ".remove_stop", function () {
  $(this).closest("div").remove(); //use closest here
  $("#add_stop_here .input-box").each(function (index) {
    $(this)
      .find("label:eq(0)")
      .attr("id", "stop" + (index + 1));

    $(this)
      .find("label:eq(0)")
      .html("Stop" + (index + 1) + '<input type="text" name="stop" />');
  });
  counter--;
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<form action="https://www.example.com" method="POST">
  <label for="stype">Service Type:</label>
  <select id="stype" name="service-type">
    <option disabled="disabled" selected="selected">Choose Service</option>
    <option value="From Airport">From Airport</option>
    <option value="To Airport">To Airport</option></select
  ><br /><br />

  <label for="fullname">Name: </label
  ><input
    id="fullname"
    name="name"
    size="20"
    type="text"
    maxlength="20"
    placeholder="John Doe"
    required
  /><br /><br />
  <label for="phone">Phone: </label
  ><input
    id="phone"
    name="phone"
    maxlength="12"
    type="tel"
    placeholder="012-345-6789"
    required
  /><br /><br />
  <label for="email">Email: </label
  ><input
    id="email"
    name="email"
    size="30"
    type="email"
    maxlength="30"
    placeholder="[email protected]"
    required
  /><br /><br />

  <label for="ptime">Pickup time </label
  ><input id="ptime" name="pickup-time" type="time" required /><br /><br />
  <label for="pdate">Pickup Date </label
  ><input id="pdate" name="pickup-date" type="date" required /><br /><br />
  <div id="add_stop_here"></div>
  <input type="button" id="add" value="+Add Stop" />
</form>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文