更改时存储在对象中的动态变量不会更新值

时间:2018-11-11 20:49:56

标签: javascript object dom ecmascript-6

我将动态变量存储在名为newEvent的对象中。变量值会更改,但是当我将它们存储在newEvent中时,它们将保持与首次加载时相同的值,并且在更新时不会更改值。这是我的代码

let headerMonths = document.getElementsByClassName('month')[0];
let headerYears = document.getElementsByClassName('year')[0]; 

let newEvent = {
    // day: parseInt(event.innerHTML),
    title: document.querySelector('#new-event-title'),
    desc: document.querySelector('#new-event-desc'),
    month: headerMonths.innerHTML,
    year: headerYears.innerHTML,
    active: document.getElementsByClassName('active')[0],
    submit: ()=>{
        if(newEvent.title.value.length===0){
            console.log('sasc');
            newEvent.title.classList.add('error');
        } else if(newEvent.desc.value.length===0) {
            newEvent.desc.classList.add('error');
        } else {
            newEventJson(newEvent.title.value, newEvent.desc.value, newEvent.month, newEvent.year, newEvent.active.innerHTML);
        }
    }
 };

 document.querySelector('#submit-event').addEventListener('click', (e)=>{
    e.preventDefault();
    newEvent.submit();
 }); 

在newEvent中唯一改变其值的变量是newEvent.title和newEvent.desc,它们是表单中html输入的内容。为什么会发生这种情况,如何获得变量的更改值?

2 个答案:

答案 0 :(得分:0)

标题和描述是唯一更改的值的原因是因为您在newEvent中将它们设置为对应的DOM元素的查询选择器结果。而其他值(包括月,年和有效)是字符串或数字/布尔值。

答案 1 :(得分:0)

我将代码更改为此

let newEvent = {
    // day: parseInt(event.innerHTML),
    title: document.querySelector('#new-event-title'),
    desc: document.querySelector('#new-event-desc'),
    month: headerMonths,
    year: headerYears,
    active: document.getElementsByClassName('active'),
    submit: ()=>{
        if(newEvent.title.value.length===0){
            console.log('sasc');
            newEvent.title.classList.add('error');
        } else if(newEvent.desc.value.length===0) {
            newEvent.desc.classList.add('error');
        } else {
            newEventJson(newEvent.title.value, newEvent.desc.value, newEvent.month.innerHTML, newEvent.year.innerHTML, newEvent.active[0].innerHTML);
        }
    }
 };

,现在值正在更新。一定是因为当我声明对象键时,在更改元素之前我已经访问了元素的当前值,并且在调用Submit函数时它从未更新,但是现在仅当我调用object时才访问元素的直接值或html。 newEvent.submit函数,这是我对那些元素所做的更改。