我正处于学习阶段,我正在研究一些旧的小型项目,并试图将旧的功能编程转移到OOP。在下面的这种情况下,我可以想象基于项目的简单性,使用基本功能会更容易,但是我只是想将其更改为OOP,所以我开始了解两者之间的区别。我遇到的问题是,尽管我有一个指向convert函数的输入onclick事件,但是当我将numberBox.value分配给我的years属性时,它仍将其读取为null(加载页面时的值),手动读取numberBox的值就很好了,并按输入的每个Event键更改每个键的输入。为什么它不能在我的物体中识别出它?
const numberBox = document.querySelector('#years');
const days = document.querySelector('#days');
const hours = document.querySelector('#hours');
const minutes = document.querySelector('#minutes');
numberBox.addEventListener('input', convert );
let converter = {
years: numberBox.value,
toDays: function () {
return this.years*365;
},
toHours: function () {
return this.years*8760;
},
toMinutes: function () {
return this.years*525600;
}
};
function convert () {
days.lastElementChild.innerHTML = converter.toDays();
hours.lastElementChild.innerHTML = converter.toHours();
minutes.lastElementChild.innerHTML = converter.toMinutes();
}
下面是我更改为OOP之前的旧功能代码。我以为两者都可以工作,但看来我错了。谢谢
function convert () {
let years = numberBox.value; // could also use THIS.value as this is the box i am inputting on
days.lastElementChild.innerHTML = years * 365;
hours.lastElementChild.innerHTML = years * 8760;
minutes.lastElementChild.innerHTML = years * 525600;
}
答案 0 :(得分:1)
numberBox.value
=> Number(numberBox.value)
。始终将文本值转换为适当的类型!function convert () {...}
添加到函数converter.years = Number(numberBox.value)
中,否则可以使用converter.years
属性,但切勿从输入中为其分配更新值。