我想在列表中添加不同的项目,然后使用“click”事件删除其中的每一项。但是,波纹管片段只允许我删除那些预设项目,而不是我添加的项目。谁能告诉我我做错了什么?
HTML
<body>
<div id="page">
<h1 id="header">List</h1>
<h2>Buy groceries</h2>
<ul>
<li id="one" class="hot"><em>fresh</em> figs</li>
<li id="two" class="hot">pine nuts</li>
<li id="three" class="hot">honey</li>
<li id="four">balsamic vinegar</li>
</ul>
<div id="newItemButton"><button href="#" id="showForm">new item</button></div>
<form id="newItemForm">
<input type="text" id="itemDescription" placeholder="Add description..." />
<input type="submit" id="addButton" value="add" />
</form>
</div>
<script src="js/jquery-1.11.0.js"></script>
<script src="js/form.js"></script>
的jQuery
$(function() {
var $newItemButton = $('#newItemButton');
var $newItemForm = $('#newItemForm');
var $textInput = $('input:text');
$newItemButton.show();
$newItemForm.hide();
$('#showForm').on('click', function(){
$newItemButton.hide();
$newItemForm.show();
});
$newItemForm.on('submit', function(e){
e.preventDefault();
var newText = $textInput.val();
$('li:last').after('<li>' + newText + '</li>');
$('li:last').attr('class','hot');
$newItemForm.hide();
$newItemButton.show();
$textInput.val('');
});
var $listItems = $('li');
$listItems.on('click', function(){
$(this).animate({
opacity: 0.0,
paddingLeft: 50
}, 500, function(){
$(this).remove();
});
});
});
答案 0 :(得分:1)
请查看以下代码段
$(function() {
var $newItemButton = $('#newItemButton');
var $newItemForm = $('#newItemForm');
var $textInput = $('input:text');
$newItemButton.show();
$newItemForm.hide();
$('#showForm').on('click', function(){
$newItemButton.hide();
$newItemForm.show();
});
$newItemForm.on('submit', function(e){
e.preventDefault();
var newText = $textInput.val();
$('li:last').after('<li>' + newText + '</li>');
$('li:last').attr('class','hot');
$newItemForm.hide();
$newItemButton.show();
$textInput.val('');
});
});
$(document).ready(function(){
$("#page").on("click","li",function(){
$(this).animate({
opacity: 0.0,
paddingLeft: 50
}, 500, function(){
$(this).remove();
});
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="page">
<h1 id="header">List</h1>
<h2>Buy groceries</h2>
<ul>
<li id="one" class="hot"><em>fresh</em> figs</li>
<li id="two" class="hot">pine nuts</li>
<li id="three" class="hot">honey</li>
<li id="four">balsamic vinegar</li>
</ul>
<div id="newItemButton"><button href="#" id="showForm">new item</button></div>
<form id="newItemForm">
<input type="text" id="itemDescription" placeholder="Add description..." />
<input type="submit" id="addButton" value="add" />
</form>
</div>
&#13;
答案 1 :(得分:0)
因为您没有将click
事件绑定到新元素,请使用class
绑定并绑定父元素,例如顶级父document
$(document).on('click', '.class', function(){
$(this).animate({
opacity: 0.0,
paddingLeft: 50
}, 500, function(){
$(this).remove();
});
});