在jQuery .each循环中访问元素

时间:2012-11-01 16:44:17

标签: javascript jquery momentjs

早上好,这是我的第二个自编js;为我的知识和风格浅浅道歉。我怀疑我目前的解决方案是泡泡糖和胶带。

我有一个有开始时间和结束时间的事件列表。它们还有一些各种各样的文本数据,这些数据会导致元素的高度发生变化。我正在使用moment.js将时间转换为适当的宽度和偏移量。

我想以尽可能压缩的格式显示元素而不重叠。到目前为止,我已经通过存储角变量并在循环的下一次迭代中比较它们来使它适用于大多数事件集;然后将当前元素向下移动到前一个元素的底部。

是否有更好的方法可以让我将事件与之前的所有事件进行比较并相应地定位?

                    $('.metro_event').each(function (i) {

        // Set Width and Left Offset based on start time and duration
        pixelScale = 1.25
        startTime = $(this).attr('start_date');
        startTime = moment(startTime);
        endTime = moment($(this).attr('end_date'));
        endTime = moment(endTime);
        duration = moment.duration(endTime - startTime);
        dayStart = moment(startTime).startOf('day');
        timeOffsex = moment.duration(startTime - dayStart);
        timeOffset = ((timeOffsex - 32400000)/60000) * 1.25;
        timeWidth = (duration/60000) * 1.25;
        $(this).css("width", timeWidth + "px");
        $(this).css("left", timeOffset + "px");

        //Get Height of Current for comparison
        currentHeight = $(this).height();
        currentBottom = currentHeight

        // Get Paramters for Previous Positioned Element

        lastWidth = $(".positioned").filter(':last').width();
        lastHeight = $(".positioned").filter(':last').height();
        lastLeft = $(".positioned").filter(':last').css("left");
        lastLeft = lastLeft.substring(0, lastLeft.length - 2);
        lastLeft = lastLeft * 1
        lastTop = $(".positioned").filter(':last').css("top");
        lastTop = lastTop.substring(0, lastTop.length - 2);
        lastTop = lastTop * 1
        lastRight = lastLeft + lastWidth;
        lastBottom = lastTop + lastHeight;

        // Compare Placement to Previous Positioned Element and Move Down as required

        if (timeOffset<lastRight && currentHeight>lastTop)
            {
            $(this).css("top", lastBottom + "px");
        }

        $(this).addClass('positioned');

        // Increment Height and Set Height of Containing Div

        $('#events').css("height", "300px");


    });

1 个答案:

答案 0 :(得分:0)

不要使用$(".positioned").filter(':last')(如果反复使用,则不要使用,但只能使用一次)。我认为你真正想要的是一个包含最后一个迭代元素的变量,不是吗?

var last = null; // or $(".positioned").filter(':last') if there are already some
$('.metro_event').each( function() {
    var $this = $(this);
    // get attributes,
    // compute moments,
    // get css styles and position values

    // Now, use the variable
    last …
    // to get position values etc of the last element
    // style $this and
    $this.addClass("positioned");

    // then, after you're done, set "last" for the next iteration
    last = $this;
});
// maybe clean the global? variable last again with
last = null;
相关问题