简体   繁体   中英

Why doesn't this remove all of the items from the <select> element?

I have a function that is supposed to remove all child elements from a <select> on the onfocus event. (this is soon to be followed by filling the <select> with values from an AJAX call) For some reason, it only removes one of the elements the first time it is called , and then proceeds to do nothing all subsequent calls. Does anyone have any clue as to why this might be happening?

JS Code:

function handle(e) {
  for(var i = 0; i < e.children.length - 1; i++) {
    e.removeChild(e.children[i]);
  }
}

i'm guessing handle() is your onfocus event handler. in which case e is your event object and doesn't have any children property

why not just use select.innerHTML = ""

So the answer is simply to remove them in inverse order, as to avoid the effects of a indexing system quite similar to the VB.NET List Class. (That is that it reorganizes itself every time a change is made.

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