日期:2014-05-16  浏览次数:20544 次

对这段代码不明白,请指教。
HTML code

<SCRIPT>
var Lastyear
function selYear(obj,Cyear){
var len=8 //select长度
var selObj=document.getElementById(obj)
var selIndex=parseInt(len/2)-1
var newOpt
var LY=Cyear-Lastyear

for (i=0;i<len;i++){
   if (selObj.options.length!=len){
     newOpt=document.createElement("OPTION")
     newOpt.text=Cyear-selIndex+i
     newOpt.value=Cyear-selIndex+i
     selObj.options.add(newOpt,i)
      if (selIndex==i) {Lastyear=newOpt.value}      
     }
    else
    {  //不明白,这段代码什么时候执行到,
     selObj.options[i].text=parseInt(selObj.options[i].text)+LY
     selObj.options[i].value=parseInt(selObj.options[i].value)+LY
     if (selIndex==i) {Lastyear=selObj.options[i].value}           
    }
 }
  selObj.selectedIndex=selIndex
}
</SCRIPT>

<SELECT id=yearSelect onChange="selYear('yearSelect',this.value)" size=1 
name=yearSelect></SELECT>
<SCRIPT>selYear('yearSelect',new Date().getFullYear()) //初试化select</SCRIPT>
 



------解决方案--------------------
初试化完里面有8个option
这时候selObj.options.length 为8 执行else 

------解决方案--------------------
JScript code

<html> 
<head> 
<title> SCROLL </title> 
<SCRIPT>
var Lastyear
function selYear(obj,Cyear){
var len=8 //select长度
var selObj=document.getElementById(obj)
var selIndex=parseInt(len/2)-1
var newOpt
var LY=Cyear-Lastyear

for (i=0;i<len;i++){
   if (selObj.options.length!=len){
     newOpt=document.createElement("OPTION")
     newOpt.text=Cyear-selIndex+i
     newOpt.value=Cyear-selIndex+i
     selObj.options.add(newOpt,i)
      if (selIndex==i) {Lastyear=newOpt.value}      
     }
    else
    {  //不明白,这段代码什么时候执行到,
     selObj.options[i].text=parseInt(selObj.options[i].text)+LY
     selObj.options[i].value=parseInt(selObj.options[i].value)+LY
     if (selIndex==i) {Lastyear=selObj.options[i].value}           
    }
 }
  selObj.selectedIndex=selIndex
}
</SCRIPT>



<body> 
<SELECT id=yearSelect onChange="selYear('yearSelect',this.value)" size=1 
name=yearSelect></SELECT>
</body> 
<SCRIPT>selYear('yearSelect',new Date().getFullYear()) //初试化select</SCRIPT>
<SELECT id=yearSelect2 onChange="selYear('yearSelect2',this.value)" size=1 
name=yearSelect2>
<option value="1999">1999</option>
<option value="1999">1999</option>
<option value="1999">1999</option>
<option value="1999">1999</option>
<option value="1999">1999</option>
<option value="1999">1999</option>
<option value="1999">1999</option>
<option value="1999">1999</option>
<option value="1999">1999</option>
</SELECT>


</html>

------解决方案--------------------
初始化时不执行,当初始化完成,以后在选中某一选项调用onChange="selYear('yearSelect',this.value)"方法时执行else