声明了变量,但从未读取过它的值JavaScript

时间:2019-10-11 09:21:59

标签: javascript function variables input slider

我的目标是在此模式下获得“关闭”按钮,以使输入保持原来的状态,即在之前按下“保存”按钮时。当我单击“取消”按钮时,它已经保存了值并重置了它们,但是声明了我的变量“ saved”,即使我在函数中使用它,它也向我显示了此错误,并且没有执行我想要的操作。

import {
    getInput, setInput
} from '../../service/data'

let close = document.getElementById('advsettings_close');
let cancel = document.getElementById('advsettings_cancel');
let save = document.getElementById('advsettings_save');
const settingsForm = document.getElementById('advsettings_form');
const settingsSliders = settingsForm.querySelectorAll('input');
var saved = false;


cancel.addEventListener('click', function() {
    cancelSettings();
});

save.addEventListener('click', function() {
    saveSettings();
});

close.addEventListener('click', function() {
    closeSettings();
});

settingsForm.addEventListener('submit', function (event){
    event.preventDefault();
});

function cancelSettings(){
    settingsSliders.forEach(function(input) {
         input.value = 5;
        console.log('Values canceled and reset');

    });
    saved = false;
}

function saveSettings(){
    settingsSliders.forEach(function(input) {
        if (input.type === 'range') {
            setInput(input.name, input.value);
            console.log('Save Value of ' + input.name + ':', input.value);
        }
    });
    saved = true;
}

function closeSettings(){
    settingsSliders.forEach(function(input) {
        if (saved = true){
            input.value = setInput(input.name, getInput(input.value));
        } else if(saved = false) {
            input.value = 5;
        }
    });
}

1 个答案:

答案 0 :(得分:0)

if confition中有一个错误:

function closeSettings(){
  settingsSliders.forEach(function(input) {
    if (saved == true){
        input.value = setInput(input.name, getInput(input.value));
    } else if(saved == false) {
        input.value = 5;
    }
 }

此外,最好直接将条件评估为布尔值:

function closeSettings(){
  settingsSliders.forEach(function(input) {
    if (saved){
        input.value = setInput(input.name, getInput(input.value));
    } else{
        input.value = 5;
    }
 }