我写了一个forEach循环,它通过一个div数组(按ID),选择具有某个类的子元素并从中删除另一个类。我在将变量转回选择器并将其连接到其他变量时遇到了一些问题。结果,我的 forEach 循环不起作用。
http://jsfiddle.net/NWmB5/7/(尝试单击其中一个链接,如果代码有效,第三项应该再次变黑)
var toDoCategories;
$(document).ready(function() {
toDoCategories = [$("#testDiv"),$("#anotherDiv"),$("thirdDiv")];
setTimelinePosition($('#thirdDiv'));
$('#targetFirstDiv').click(function() {
setTimelinePosition($('#anotherDiv'));
});
$('#targetSecondDiv').click(function() {
setTimelinePosition($('#testDiv'));
});
});
/* Show current position on timeline */
function setTimelinePosition($position) {
var $theTimelineTrigger = $('span.timelineTrigger');
toDoCategories.forEach(function(currentCategory) {
var $deselectTimelinePositionElement = $(currentCategory, $theTimelineTrigger);
$($deselectTimelinePositionElement).removeClass('currentPosition');
});
它应该像
$(document).ready(function () {
var $toDoCategories = $("#testDiv, #anotherDiv, #thirdDiv"); //NOTE HERE
setTimelinePosition('#thirdDiv');
$('#targetFirstDiv').click(function () {
setTimelinePosition('#anotherDiv');
});
$('#targetSecondDiv').click(function () {
setTimelinePosition('#testDiv');
});
/* Show current position on timeline */
function setTimelinePosition(position) {
$toDoCategories.find('.currentPosition').removeClass('currentPosition')
$(position).find('.timelineTrigger').addClass('currentPosition');
}
});
演示:小提琴
另一种方法:小提琴