命名函数工作,功能相同但anon不起作用

时间:2014-05-15 21:20:40

标签: javascript jquery html5 function anonymous-function

我无法弄清楚为什么第一个代码块在for循环中调用外部命名函数...但是当我使用anon函数重写它时,只有迭代中的最后一个元素才会接收到效果。

您认为发生了什么?

   ////// Section Setup //////
    // Setup each sections mouse over event
    for(var i = 0; i < $(".section").length; i++)
    {
        var currentSection = $(".section")[i];
        var currentSectionOver = $(".sectionOver")[i];

        setupSection(currentSection, currentSectionOver);
    }

    function setupSection(section, sectionOver)
    {
        $(sectionOver).addClass("hide");
        $(section).mouseenter(
            function(){
                $(sectionOver).removeClass("hide");
        });

        $(section).mouseleave(
            function(){
                $(sectionOver).addClass("hide");
        });
    };
    ///// Section Setup End //////

    // WHY DOESN"T THIS WORK - Same logic, just anonymous!
    ////// Section Setup //////
    // Setup each sections mouse over event
    for(var i = 0; i < $(".section").length; i++)
    {
        var currentSection = $(".section")[i];
        var currentSectionOver = $(".sectionOver")[i];

        $(function ()
        {
            $(currentSectionOver).addClass("hide");
            $(currentSection).mouseenter(
                function(){
                    $(currentSectionOver).removeClass("hide");
                    console.log("remove hide");
            });

            $(currentSection).mouseleave(
                function(){
                    $(currentSectionOver).addClass("hide");
                    console.log("add hide");
            });
        });
    }
    ///// Section Setup End //////

0 个答案:

没有答案