首页 > 解决方案 > Content Editable = true,但一次只取一个值

问题描述

我正在做一个简单的项目,我需要使列表中的项目可编辑,然后更新一个 JS 项目来存储它。

我正在使用 Content Editable = True,当我注释掉我的 handleItemEdit 函数时它可以工作,但是当我打开它时,我一次只能插入一个字符,迫使我继续点击编辑。

显然这个问题源于我的功能,但我似乎无法弄清楚为什么。

//Responsible for listening for an edit and updating my object with the new text.

function handleEditItem() {
    $('.js-shopping-item').on('input', function(event) {
        const itemIndex = getItemIndexFromElement(event.currentTarget); //assigning the index of the the editted item to itemIndex
        const updatedItem = STORE.items[itemIndex];
        updatedItem.name = event.currentTarget.innerHTML;
        renderShoppingList();
    });
}


//Returns the index of an Item in the Store
function getItemIndexFromElement(item) {
    const itemIndexString = $(item)
        .closest('.js-item-index-element')
        .attr('data-item-index');
    return parseInt(itemIndexString, 10);

}

//Function responsible for returning the template HTHML to insert into the html.

function generateItemElement(item) {
    let itemIndex = STORE.items.indexOf(item);
    return `
    <li class="js-item-index-element" data-item-index="${itemIndex}">
      <span contentEditable='true' class="shopping-item js-shopping-item ${item.checked ? 'shopping-item__checked' : ''}">${item.name}</span>
      <div class="shopping-item-controls">
        <button class="shopping-item-toggle js-item-toggle">
            <span class="button-label">check</span>
        </button>
        <button class="shopping-item-delete js-item-delete">
            <span class="button-label">delete</span>
        </button>
      </div>
    </li>`;
}

标签: javascriptjquerycontenteditable

解决方案


推荐阅读