简体   繁体   中英

How to delete a specific item from a drop-down list?

How can the user delete a specific item from the drop-down list, instead of the entire list from the chosen item and onwards?

<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);
}

Here is the code I have for adding the history to the drop-down list, and for the undo button.

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);

It would be perfect if the only the selected item from the drop-down list is deleted. Entire code: JS Bin

you are probably looking for the Array​.prototype​.splice() method

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

this will remove the selectIndex from the dropdown, but I'm not sure if you're canvas logic is working though, unless that it is doing what you'd expected.

    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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM