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

问个很简单的js程序问题
js代码中 两次alert(month[i]); 第一次就能输出 我想要的结果,第二次就是undefine了,我在想是不是作用域的问题。。 让那个onmouseover= function形成的闭包 所以里面就读取不到i的值了啊? 请教高手 请改怎么改改。。。


JScript code

function monthList(data){
    var month = new Array(data.January,data.February,data.March,data.April,data.May,data.June,data.July,data.August,data.September,data.October,data.November,data.December);//创建数组
    var nianLi = document.getElementById("nianLi").getElementsByTagName("li");
    var conTent = document.getElementById("content");
    for(var i=0;i<month.length;i++){
        
        //鼠标浮动到1-12月以后 弹出相应数字
        nianLi[i].index = i+1;
                alert(month[i]);
        nianLi[i].onmouseover = function(){
                        alert(month[i]);
            conTent.innerHTML = ""+this.index+"月"+month[i];
        }
        nianLi[i].onmouseout = function(){
            conTent.innerHTML = "";
        }
    
    }
};

monthList({
    January:"出去玩",
    February:"玩什么",
    March:"玩玩玩", 
    April:"哈哈", 
    May:"呵呵", 
    June:"嘿嘿", 
    July:"嘻嘻", 
    August:"吼吼", 
    September:"好好玩", 
    October:"玩玩玩", 
    November:"呵呵呵", 
    December:"嘻嘻嘻"
});





HTML code

<div class="nianLi">
    <ul id="nianLi">
        <li>1月</li>
        <li>2月</li>
        <li>3月</li>
        <li>4月</li>
        <li>5月</li>
        <li>6月</li>
        <li>7月</li>
        <li>8月</li>
        <li>9月</li>
        <li>10月</li>
        <li>11月</li>
        <li>12月</li>
    </ul>
    <div style="clear:left"></div>
    <div id="content"></div>
</div>



CSS code

ul,li{ padding:0; margin:0; list-style:none;}
.nianLi{ width:162px; height:216px; position:relative;}
.nianLi ul li{ width:50px; height:50px; float:left; text-align:center; font:100 12px/50px "\5B8B\4F53"; border:1px solid #000; margin:0 2px 2px 0; cursor:pointer;}
#content{ position:absolute; width:80px; height:80px; border:1px solid #000; left:200px; top:0; padding:10px;}



------解决方案--------------------
JScript code
 nianLi[i].index = i+1;//和这个一样用呀,你这不是自己已经用了么??
 nianLi[i].month=month[i];//
        nianLi[i].onmouseover = function(){
            conTent.innerHTML = this.index+'月'+this.month;
        }

------解决方案--------------------
这样可以

function monthList(data){
var month = new Array(data.January,data.February,data.March,data.April,data.May,data.June,data.July,data.August,data.September,data.October,data.November,data.December);//创建数组
var nianLi = document.getElementById("nianLi").getElementsByTagName("li");
var conTent = document.getElementById("content");
for(var i=0;i<month.length;i++){

//鼠标浮动到1-12月以后 弹出相应数字
nianLi[i].index = i+1;
alert(month[i]);
(function(j) {
nianLi[i].onmouseover = function(){
alert(month[j]);alert(j);
conTent.innerHTML = ""+this.index+"月"+month[j];
}
})(i);

nianLi[i].onmouseo