[英]Multiple buttons per item instead of just one button per item in my Shopping List App?
我正在制作购物清单应用程序。 我可以将项目添加到列表中,一旦它们出现,我就做到了这样,每个项目旁边都会出现一个按钮。 该按钮就在那里,您可以点击它并在准备好后从列表中删除您的项目。
这里的问题是,在添加几个项目后,按钮会自行增加。 基本上,代替一个项目只有一个按钮,每个项目有多个按钮随着列表的增加。 我只需要每个项目一个按钮。 你能看一下我的代码和帮助吗? 非常感谢!
$(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>
为什么每次都复制按钮? 他有身份证,所以你不能复制他。
@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>
https://jsfiddle.net/62afjy7q/
基本上,我改变了隐藏/显示按钮的方式(现在用css隐藏),并在附加到每个按钮时克隆它。 我修改了一些html,将第一组内容放在自己的div中
<div class="container">
<div class="input-container">
<input class="text-box" placeholder="Please enter an item">
<button id="send">submit</button>
<button id="removebox">X</button>
</div>
</div>
--- css ---
.input-container #removebox {
display: none
}
--- js ---
function addBox(){
$('.container li:last-child').append($('#removebox').clone());
//$('#removebox').show();
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.