开始的代码,使用for循环来一个个监测是否被选中:
- functionmoveOption2(sourceSelect,destSelect){
- varsourceOptions=sourceSelect.options;
- for(vari=sourceOptions.length-1;i>-1;i--){
- varoption=sourceOptions[i];
- if(option.selected){
- varnewOption=newOption(option.text,option.value);
- destSelect.add(newOption);
- sourceSelect.remove(i);
- destSelect.scrollIntoView(false);
- }
- }
- }
优化后的代码,只检查被选中的代码,巧妙的使用了selectedIndex的特性,每次上一个selected option被删除,则selectedIndex就变成下一个selected option的index值:
- functionmoveOption(sourceSelect,destSelect){
- varsourceOptions=sourceSelect.options;
- varremoveIndex=sourceSelect.selectedIndex;
- while(removeIndex!=-1){
- varremoveOption=sourceOptions[removeIndex];
- varnewOption=newOption(removeOption.text,removeOption.value);
- destSelect.add(newOption);
- sourceSelect.remove(removeIndex);
- removeIndex=sourceSelect.selectedIndex;
- }
- }