我尝试使用编辑按钮制作待办事项列表,点击该按钮会使添加的项目可编辑,但遇到问题。我创建了按钮和所有内容,但是当我点击它时没有任何反应。任何建议将不胜感激!
的JavaScript
function editItem(){
var parent = $(this).parent();
if (!parent.hasClass('edit')) {
parent.addClass('edit');
}else if (parent.hasClass('edit')) {
var editTask = $(this).prev('input[type="text"]').val();
var editLabel = parent.find('label');
editLabel.html(editTask);
parent.removeClass('edit');
}
$(function(){
$(document).on('click', 'edit', editItem)
});
答案 0 :(得分:2)
您似乎定位<edit>
,您应该使用.edit
:
$(function(){
$(document).on('click', '.edit', editItem);
});
工作代码段
$(function () {
function addItem () {
// append to the list
$("#todo-items").append('<li><span>' + $("#todo").val() + '</span> <small><a href="#edit">Edit</a> • <a href="#delete">Delete</a></small></li>');
// clear the text
$("#todo").val("");
}
$("#todo").keydown(function (e) {
// if enter key pressed
if (e.which == 13)
addItem();
});
// on clicking the add button
$("#add").click(addItem);
// delegate the events to dynamically generated elements
// for the edit button
$(document).on("click", 'a[href="#edit"]', function () {
// make the span editable and focus it
$(this).closest("li").find("span").prop("contenteditable", true).focus();
return false;
});
// for the delete button
$(document).on("click", 'a[href="#delete"]', function () {
// remove the list item
$(this).closest("li").fadeOut(function () {
$(this).remove();
});
return false;
});
});
* {font-family: 'Segoe UI'; margin: 0; padding: 0; list-style: none; text-decoration: none;}
input, li {padding: 3px;}
#todo-items small {display: inline-block; margin-left: 10px; padding: 2px; vertical-align: bottom;}
#todo-items span:focus {background-color: #ccf;}
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<input type="text" id="todo" />
<input type="button" value="Add" id="add" />
<ul id="todo-items"></ul>