我想在我的页面上为一系列“点击”事件创建一个For循环。我正在创建一个时间表,单击“日”按钮将在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');
});
})
}
});
当我在例如具有确切值时,JavaScript工作正常"#cwt-button1"
当我在循环中连接'i'计数器时,它不起作用。
谁能看到我哪里出错了?或者我做了JavaScript无法处理的事情?
答案 0 :(得分: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');
});
});
});
});