6

我想为我的页面上的一系列“点击”事件创建一个 For 循环。我正在创建一个时间表,单击 Day 按钮将在 div 框中显示分配给该天的事件。
HTML

<div class="cwt-buttons">
<a id="cwt-button1">Monday</a>
<a id="cwt-button2">Tuesday</a>
<a id="cwt-button3">Wednesday</a>
<a id="cwt-button4">Thursday</a>
<a id="cwt-button5">Friday</a>
<a id="cwt-button6">Saturday</a>
<a id="cwt-button7">Sunday</a>
</div>

<div id="cwt-timetable">
<div class="current">Housework</div>
<div class="cwt-Day1">Kickboxing</div>
<div class="cwt-Day2">Homework</div>
<div class="cwt-Day3">Yoga</div>
<div class="cwt-Day4">Eating</div>
<div class="cwt-Day5">Fasting</div>
<div class="cwt-Day6">Running</div>
<div class="cwt-Day7">Funeral</div>
</div>

JS

$(function() {
    for ( var i = 1; i < 8; i++ ) {
        var clickedButton = $("#cwt-button"+i);
        $(clickedButton).click(function() {
        var currentDay = $('#cwt-timetable div.current');
        var selectedDay = $('#cwt-timetable div.cwt-Day'+i);
        currentDay.removeClass('current').addClass('previous');
        (selectedDay).css({ opacity: 0.0 }).addClass('current').animate({ opacity: 1.0 }, 1000,
        function() {
            currentDay.removeClass('previous');
        });     
    })
    }
});

当我在 eg 中有确切的值时,JavaScript 工作正常。当我"#cwt-button1"
在循环中连接“i”计数器时,它只是不起作用。

谁能看到我哪里出错了?还是我做了一些 JavaScript 无法处理的事情?

4

1 回答 1

2

这只是每天被多次询问的老问题。在循环中创建的所有函数都在同一个变量范围内创建,因此它们共享同一个i变量。

要确定一个变量的范围,您需要一个函数调用。jQuery$.each()是一种方便的方法:

$(function () { // -----------v-----scoped to the function
    $.each(Array(7), function(i) {
        var clickedButton = $('#cwt-button' + (++i));

        $(clickedButton).click(function () {
            var currentDay = $('#cwt-timetable div.current');

            // --------using scoped `i`------------------------v
            var selectedDay = $('#cwt-timetable div.cwt-Day' + i);
            currentDay.removeClass('current').addClass('previous');
            (selectedDay).css({
                opacity: 0.0
            }).addClass('current').animate({
                opacity: 1.0
            }, 1000, function () {
                currentDay.removeClass('previous');
            });
        });
    });
});
于 2013-09-16T02:42:34.907 回答