首页 > 解决方案 > 如何从下拉列表中删除特定项目?

问题描述

用户如何从下拉列表中删除特定项目,而不是从所选项目中删除整个列表及以后?

<label> 
History:
    <select id="historySelect">
    </select>
</label>

<label>
    <input type="button" id="cmbDelete" value="Undo">
</label>


  var history = [];
  var historySelect

historySelect = document.getElementById('historySelect')
historySelect.addEventListener('change', ()=>{
restoreHistoryAction(historySelect.value)
    })

function drawCanvas() {
    contextTmp.drawImage(canvas, 0, 0);
history.push(contextTmp.getImageData(0,0,canvasTmp.width,canvasTmp.height))
        updateHistorySelection()
    context.clearRect(0, 0, canvas.width, canvas.height);
}

这是我将历史记录添加到下拉列表和撤消按钮的代码。

function cmbDeleteClick(){
 if(history.length<=1)
  return

    history.pop()
    contextTmp.putImageData(history[history.length-1],0,0)
    updateHistorySelection()
  }

    function updateHistorySelection(){
    historySelect.innerHTML = ''

    history.forEach((entry,index)=>{
      let option = document.createElement('option')
      option.value = index
      option.textContent = index===0 ? 'Start ' : 'Action '+index
      historySelect.appendChild(option)
    })

    historySelect.selectedIndex = history.length-1
  }

  function restoreHistoryAction(index){
    contextTmp.putImageData(history[index],0,0)
  }

  cmbDelete = document.getElementById("cmbDelete");
  cmbDelete.addEventListener("click",cmbDeleteClick, false);

如果从下拉列表中唯一选择的项目被删除,那将是完美的。完整代码:JS Bin

标签: javascripthtml5-canvas

解决方案


您可能正在寻找Array​.prototype​.splice()方法

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

这将从selectIndex下拉列表中删除,但我不确定你的画布逻辑是否正常工作,除非它正在做你所期望的。

    function cmbDeleteClick(){
      if(history.length<=1) return;

      var historyIndex = document.getElementById("historySelect").selectedIndex;
      var historyItems = history.splice(historyIndex, 1);
      contextTmp.putImageData(historyItems[0],0,0);

      updateHistorySelection();
    }

推荐阅读