javascript - 如何从下拉列表中删除特定项目?
问题描述
用户如何从下拉列表中删除特定项目,而不是从所选项目中删除整个列表及以后?
<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
解决方案
您可能正在寻找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();
}
推荐阅读
- powershell - 如何在 Windows 上使用带有远程 pc 的 PowerShell 远程调用应用程序(.exe 文件)?
- android - Android 在深色模式下更改工具栏背景颜色
- c++ - 功能完美,但返回后改变值
- node.js - 如何解决我的 heroku 应用程序上的“不安全”警告?
- c# - 用于替换值的 REGEX 帮助
- c# - 如何调用返回列表的存储过程
使用 .net 核心实体框架 - embedded - USART中idle和break字符的目的是什么?
- javascript - 在 Apollo Express GraphQL 中出现错误:错误:模式必须包含唯一命名的类型,但包含多个名为“DateTime”的类型
- python - How to Write a Cleaner and performant code with Pandas while reading CSV
- apache-kafka - KSQL 无法加入加入的流,ksql 中的菊花链