Accessing an objects property inside a function

梦想与她 提交于 2020-08-10 21:48:06

问题


I'm trying to access objects properties inside an array in my code to render the text values of input boxes restored after a refresh from the local storage but for some reason when I try to run the for loop inside my appStart() function it gives me: "Uncaught TypeError: Cannot read property 'id' of undefined at appStart". Any insiights of why this happens and how to fix it will be greatly appreciated.

const currentDayPlaceholder = $("#currentDay");
const timeInTimeBlocks = $(".input-group-text");
const timeBlockInput = $(".form-control");
const saveButton = $(".saveBtn");
let numericCurrentTime = parseInt(moment().format("H A"));
let notes = [];


currentDayPlaceholder.append(moment().format('dddd, MMMM Do'));

function timeBlocksColorDeterminator() {

    for (let i = 0; i < timeInTimeBlocks.length; i++) {

        let numericTimeinTimeBlock = parseInt($(timeInTimeBlocks[i]).text());
        if ($(timeInTimeBlocks[i]).hasClass('pm')) {
            numericTimeinTimeBlock += 12;
        }
        if (numericCurrentTime === numericTimeinTimeBlock) {
            $(timeBlockInput[i]).addClass("present");
        } else if (numericCurrentTime > numericTimeinTimeBlock) {
            $(timeBlockInput[i]).addClass("past");
        } else {
            $(timeBlockInput[i]).addClass("future");
        }

    }
}

function appStart() {

    notes = JSON.parse(localStorage.getItem("timeBlockNotes"));

    for (let i = 0; i < timeBlockInput.length; i++) {
        if (i === parseInt(notes[i].id)) {
            timeBlockInput[i].value = notes[i].value;
        }
    }
}
appStart();

saveButton.on("click", function () {
    console.log("click");
    notes.push({
        value: timeBlockInput[this.id].value,
        id: this.id
    })
    localStorage.setItem("timeBlockNotes", JSON.stringify(notes));
})

timeBlocksColorDeterminator();

回答1:


I have fixed this after changing my appStart() function to this :

function appStart() {

    notes = JSON.parse(localStorage.getItem("timeBlockNotes"));

    for (let i = 0; i < notes.length; i++) {

        timeBlockInput[parseInt(notes[i].id)].value = notes[i].value;

    }
}

thank you guys for your comments and answers.



来源:https://stackoverflow.com/questions/62443915/accessing-an-objects-property-inside-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!