用户如何从下拉列表中删除特定的项目,而不是从所选项目及以后的整个列表中删除?
<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);
如果删除下拉列表中唯一选中的项目,那将是完美的。 Entire code: JS Bin
答案 0 :(得分:1)
您可能正在寻找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();
}