【发布时间】:2014-06-02 10:39:57
【问题描述】:
我正在使用 jQuery 构建一个购物应用程序。在文本输入中输入文本并按回车键会添加一个新项目。将鼠标悬停在项目上并单击删除将删除该项目。点击一个项目会将其划掉。
在文本输入中添加新列表项后,应用了正确的类,但用于删除和划掉项目的 jquery 函数不起作用。例如,“删除”跨度应在页面加载时隐藏,并在您将鼠标悬停在列表项上时出现,但对于新列表项,删除跨度始终显示。为什么我的函数不适用于我通过输入添加的新项目?
HTML:
<div class="wrapper">
<form onsubmit="return false"> <!--return false prevents enter from refreshing page -->
<input type="text" placeholder="I need to buy..." name="shopping_item">
</form>
<ul class="instructions">
<li>Click on tile to mark complete</li>
<li class="divider">|</li>
<li>Hover and click “Delete” to delete</li>
</ul>
<section>
<h1 class="outline">Shopping List Items</h1>
<ul class="shopping_item_list">
<li class="tile">Flowers<span class="delete">Delete</span></li>
<li class="tile middle">A gift card for mom's birthday<span class="delete">Delete</span></li>
<li class="tile">A birthday card<span class="delete">Delete</span></li>
<!-- Do I need to have divs to clear? It looks like it works without them. -->
<li class="tile">Yogurt<span class="delete">Delete</span></li>
<li class="tile middle">Applesauce<span class="delete">Delete</span></li>
<li class="tile">Iced tea<span class="delete">Delete</span></li>
<li class="tile">Ice cream<span class="delete">Delete</span></li>
<li class="tile middle">Laundry detergent<span class="delete">Delete</span></li>
<li class="tile">Sandwich bags<span class="delete">Delete</span></li>
</ul>
</section>
</div><!--end wrapper-->
CSS:
.shopping_item_list .delete {
display: block;
position: absolute;
bottom: 0;
left: 0;
right:0;
background-color: #000;
padding-top:10px;
padding-bottom: 10px;
font-family: Verdana, sans-serif;
font-size:18px;
text-align: center;
}
.deleteAction {
background-color:#b7b7b7 !important;
text-decoration:line-through;
color:#e1e1e1;
}
JQuery:
$(document).ready(function() {
//add list item
$("input[name='shopping_item']").change(function() {
var item = $(this).val();
$("<li class='tile'>" + item + "<span class='delete'>Delete</span>" + "</li>").prependTo(".shopping_item_list");
$(".tile").removeClass("middle");
$(".shopping_item_list li:nth-child(3n+2)").addClass("middle");
});
// hide delete button
$(".delete").hide();
// delete square
$(".tile").hover(function() {
$(this).find(".delete").toggle();
});
$(".tile").on("click", ".delete", function() {
$(this).closest("li.tile").remove();
$(".tile").removeClass("middle");
$(".shopping_item_list li:nth-child(3n+2)").addClass("middle");
});
// cross off list
$(".tile").click(function() {
$(this).toggleClass("deleteAction");
});
}); // end of ready function
【问题讨论】: