编辑动态生成的列表项的文本,其中没有图标

时间:2018-08-25 13:06:43

标签: javascript edit

我正在玩着名的任务列表应用程序练习,并希望通过每个动态添加的<li>中的编辑按钮来扩展它。

目前,我的<li>看起来像这样:

<li class="list-item">
  "some text from my input"
  <a class="delete-task">... //delete icon
  <a class="edit-task">...   //edit icon
</li>

现在,如果我将<li>设置为contenteditable='true',则可以编辑它的文本,但也可以删除这些图标,甚至在其中写一些东西,这很疯狂。

问题:使用香草js,如何编写一个函数,在单击编辑图标后,该函数仅允许我更改文本?

下面是一个链接,可显示我的<li>https://i.stack.imgur.com/kt4zM.jpg

1 个答案:

答案 0 :(得分:0)

将文本包装在<span>标记中,仅使其可编辑。

document.querySelector("a.edit-task")
  .addEventListener("click", function(e) {
    e.preventDefault();

    var span = this.previousElementSibling;
    span.contentEditable = span.contentEditable == "true" ? "false" : "true";
  });
.list-item span { margin-right: 10px; }
.list-item img { height: 16px; }
span[contenteditable="true"] { background-color: yellow; }
<ul>
  <li class="list-item">
    <span>lorem ipsum dolor amet...</span>
    <a class="edit-task" href="#">
      <img src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDQ1IDQ1IiBoZWlnaHQ9IjQ1cHgiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCA0NSA0NSIgd2lkdGg9IjQ1cHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxnPjxyZWN0IGZp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