开始的代码,使用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;
- }
- }
本文介绍了一种优化的JavaScript函数,用于在两个选择框之间高效地移动已选中的选项。通过利用selectedIndex属性,新方法能够避免遍历所有选项,仅处理被选中的项。
1106

被折叠的 条评论
为什么被折叠?



