jQuery - ForEach循环中的变量选择器

时间:2014-01-10 13:30:28

标签: javascript jquery foreach

我编写了一个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');
});

1 个答案:

答案 0 :(得分:1)

应该像

一样简单
$(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');
    }
});

演示:Fiddle


另一种方法:Fiddle