javascript - 在我的购物 list 应用程序中,每件商品有多个按钮,而不是每件商品只有一个按钮?

标签 javascript jquery html css

我正在制作一个购物 list 应用程序。我可以将元素添加到列表中,一旦它们出现,我就这样做了,以便每个元素旁边都会出现一个按钮。该按钮就在那里,您可以单击它并在准备就绪时从列表中删除您的元素。

这里的问题是,在您添加一些元素后,按钮会自行增加。基本上,不是只有一个按钮对应一个元素,而是随着列表的增加,每个元素都有多个按钮。每个元素我只想要一个按钮。你能看看我的代码并帮忙吗?非常感谢!

$(document).ready(function() {

  $('#removebox').hide();

  //When you click send it sends the item to the list
  $('#send').click(function() {
    var userMessage = $('.text-box').val();
    $('.text-box').val('');

    //If theres nothing in the text-box and send is clicked an alert pops up
    if (!userMessage) {
      alert("Please add some items to the list!")
    } else {
      //This appends the item typed into the text-box to the list
      $('.container').append('<li>' + userMessage + '</li>');
      addBox();
    }
  });


  //This adds the remove button next to each item in the list      
  function addBox() {
    $('.container li').append($('#removebox'));
    $('#removebox').show();

  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title" width="100%">
  <p> Shopping List</p>
</div>

<div class="container">
  <input class="text-box" placeholder="Please enter an item">
  <button id="send">submit</button>
  <button id="removebox">X</button>
</div>

最佳答案

为什么每次都要复制按钮?他有一个 ID,所以无论如何你都不能复制他。

正如@tyler mackenzie 正确指出的那样,真正的问题是您的'.container li' 选择器会找到所有点,而不仅仅是最后一个点。

所以这里有一些代码可以解决这些问题:

$(document).ready(function() {
  //When you click send it sends the item to the list
  $('#send').click(function() {
    var userMessage = $('.text-box').val();
    $('.text-box').val('');

    //If theres nothing in the text-box and send is clicked an alert pops up
    if (!userMessage) {
      alert("Please add some items to the list!")
    } else {
      //This appends the item typed into the text-box to the list
      var remBtn = $('<button class="removebox">');  // this creates a new button element
      remBtn.text('X');
      var li = $('<li>');
      li.text(userMessage);
      li.append(remBtn);
      $('.container').append(li);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title" width="100%">
  <p> Shopping List</p>
</div>

<div class="container">
  <input class="text-box" placeholder="Please enter an item">
  <button id="send">submit</button>
</div>

关于javascript - 在我的购物 list 应用程序中,每件商品有多个按钮,而不是每件商品只有一个按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46899265/

相关文章:

javascript - 通过javascript删除上一个和下一个HTML元素

javascript - 将 var 设置为 .text()

javascript - 是否有与 React Fragments 等效的 Angular 2+?

javascript - 如何在 <head> 中使用 getElementsByClassName 访问元素

javascript - javascript中promise的执行顺序是怎样的?

javascript - 使用 jQuery 在 XML 文件中搜索元素

javascript - php发送脚本后引导模式在同一页面中打开

jquery - 如何根据元素的内容添加类?

javascript - CSS/HTML 通过 Javascript 动态调整 Iframe 的大小

html - 如何将多个 div 标签放置在彼此之上