【问题标题】:To-Do list with edit button Jquery带有编辑按钮 Jquery 的待办事项列表
【发布时间】:2016-01-01 21:24:15
【问题描述】:

我正在尝试使用编辑按钮制作待办事项列表,单击该按钮后,添加的项目可编辑,但我遇到了问题。我已经创建了按钮和所有内容,但是当我单击它时没有任何反应。任何建议将不胜感激!

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)
});

【问题讨论】:

  • 您使用"edit" 作为选择器,它选择<edit></edit> 元素。你的文档中有这样的元素吗?
  • 好电话@Vohuman;对于 class edit,您可能想尝试 .edit
  • 嗨,我试过了,但似乎没有用。我创建了一个 JSFiddle,你能检查一下看看有什么问题吗?多谢你们! jsfiddle.net/Rassisland/gv0qkrpp
  • @praveen Kumar 感谢您的帮助!稍后我将通过它,但可能有一些问题!非常感谢您的帮助!

标签: javascript jquery edit


【解决方案1】:

看起来你的目标是<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> &bull; <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>

【讨论】:

  • 哦,我明白了!这是错误的,但是单击编辑按钮仍然没有结果。我添加了一个 JSFiddle,也许对你有帮助?谢谢!
  • @Rassisland 当然,我会尝试检查一下。
  • @Rassisland 我已经更新了你的代码哥们。有很多错误:jsfiddle.net/9v5dwxLv
  • 感谢所有帮助,我的代码现在看起来好多了!我无法让编辑按钮正确格式化。我希望按钮更新新文本并在单击输入时退出编辑选项,但现在它跳到新行。有什么想法吗?
  • 太棒了!你真的帮了我这个忙。我很感激!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-09
相关资源
最近更新 更多