简体   繁体   中英

Having an Issue Defining Variable Globally In jquery

I'm trying to keep what I save in local storage on the page, that way if I were to refresh I would still have whatever I entered in the textarea box.

However I'm not sure if it's because I am using a variable that assigns to e.target then the relative path to what I am trying to save, but when I console.log my variable it says it's not defined and I'm assuming that my issue is because I don't fully understand jQuery.

function updateHours() {}

function handleSave(e) {
  var value = $(e.target).siblings('.description').val()
  var hour = $(e.target).closest('.time-block').attr('id')
  localStorage.setItem(hour, value)
}

function main() {
  updateHours();
  $(document).on('click', '.saveBtn', handleSave)
  console.log(localStorage.getItem(value))
}

$(document).ready(main)

Try something like this:

function updateHours(){
    document.querySelectorAll('.time-block').forEach(el => {
        const savedValue = localStorage.getItem(el.id);
        const description = el.querySelector('.description');
        if (savedValue && description) {
            console.debug("Load value", el.id, savedValue);
            description.value = savedValue;
        }
    });
}

function handleSave(e){
    const el = e.target.closest('.time-block');
    if (!el) { return; }
    
    const description = el.querySelector('.description');
    if (!description) { return; }
    
    console.debug("Save value", el.id, description.value);
    localStorage.setItem(el.id, description.value);
}

function main(){
    updateHours();
    
    document.addEventListener('click', e => {
        if (!e.target.classList.contains('saveBtn')) { return; }
        handleSave(e);
    });
}

window.addEventListener('DOMContentLoaded', main);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM