在数组中动态创建新元素并更新所有后续元素的ID

时间:2016-09-09 13:58:21

标签: javascript jquery arrays dom dynamic

我正在研究基于时间轴的日记/日记,其中我有一些代表各个条目的JS对象。每个对象都有一个基于其在数组中的位置的ID。问题是我希望能够在数组中的特定位置插入一个条目,然后更新所有条目的ID以匹配它们在数组中的新位置。 Figure 1

图1:数组中有两个ID为0和1的条目。我在第二个条目(id 1)中单击按钮,在此条目之前添加新条目。新条目将具有“id = 1”,并且以下所有条目都需要将其ID更新为“id + = 1”,因此不会有重复的ID。

现在这是我的问题。在创建新条目之后(或之前),我似乎无法更新ID。这是我的代码:

创建新的Day对象并将其添加到数组

//currentID = ID of the entry I'm creating the new one from
//new Day(id, name, date, desc);
//daysArray is the array containing entry objects

var dayToCreate = new Day(currentID,
    $newDayName.val(),
    $newDayDate.val(),
    $newDayDescription.val());
daysArray.splice(currentID, 0, dayToCreate); //

更新所有后续数组元素的ID以匹配其新数组位置

var ii = daysArray.length - 1;
for (; ii > currentID; ii--) {
    daysArray[ii].id = ii;
    $( ".day#" + ii - 1 ).attr("id", ii); //Change ID of the DOM element
}

为新条目创建DOM

drawDay(currentID).insertBefore( $( ".day#" + currentID ) );

drawDay函数

function drawDay(dayId) {
    var $drawDiv = $( "<div class='day' id='" + daysArray[dayId].id + "'></div>" );

    //Return DOM for the day
    return $drawDiv;
}

1 个答案:

答案 0 :(得分:0)

Sub Single()

Dim DateRng As Range, DateCell As Range, DateRngPay As Range
Dim cellA As Range
Dim cellB As Range
Dim myColor As Variant

Set DateRng = ActiveWorkbook.Worksheets("SS").Range("B11:F16,I11:M16,P11:t16,B19:F24,I19:M24,P19:t24,B27:F32,I27:M32,P27:t32,B35:F40,I35:M40,P35:t40")
Set DateRngPay = ActiveWorkbook.Worksheets("PS").Range("C2:C67")
myColor = Array("38")

If ActiveWorkbook.Worksheets("Info").Range("B67") = 1 Then
    With DateRng
            .Interior.ColorIndex = xlColorIndexNone
            '.Borders.LineStyle = xlContinuous
            .Borders.ColorIndex = 1
            .Borders.Weight = xlHairline
    For Each cellA In DateRng
        For Each cellB In DateRngPay
                If cellB.Value > "" And cellA.Value > "" And cellB.Value = cellA.Value Then
                With cellA.Borders
                    .ColorIndex = myColor
                    .Weight = xlMedium
                End With
                Exit For
            End If
        Next cellB
    Next cellA
    End With
End If
End Sub

转到

var ii = daysArray.length - 1;
for (; ii > currentID; ii--) {
    daysArray[ii].id = ii;
    $( ".day#" + ii - 1 ).attr("id", ii); //Change ID of the DOM element
}

array.splice(start,deleteCount [,item1 [,item2 [,...]]])正在更改数组中的索引,所以你可以只使用索引作为ID吗?

另一种方法可能是在一年中的每一天使用365个项目的数组。但这会更低效。

或者让ID按条目计算,但在此使用日期:id ='“+ daysArray [dayId] .id +”'