我正在制作一个购物 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/