function weatherStation(place) {
this.name = place;
this.regn = 0;
this.vind = 0;
this.temperatur = 0;
}
因此,基本上,此功能将创建weatherStation类的对象。我想知道,例如当我赚了很多钱
var so = new weatherStation("Sola");
so.regn = regn;
so.vind = vind;
so.temperatur = temperatur;
var va = new weatherStation("Valand");
va.regn = regn;
va.vind = vind;
va.temperatur = temperatur;
var si = new weatherStation("Sinnes");
si.regn = regn;
si.vind = vind;
si.temperatur = temperatur;
我怎么能遍历这一切,因为我想将它们打印出到html中,但是,我不想一一打印出它们,因为会有一段时间我不这样做不知道我有多少。
有没有一种方法可以使我每次单击按钮时都创建一个新对象而不会覆盖最后一个?
答案 0 :(得分:1)
添加了一些操作来做出答案verifiable,但是从本质上讲,您希望将每个已创建的元素推入数组,然后要基于数组来呈现元素。这一切都是在事件触发器中完成的,但是如果需要多个不同的数组上下文,可以轻松地将render函数拉出。
// weather station object
function WeatherStation(place, regn = 0, vind = 0, temperatur = 0) {
this.name = place;
this.regn = regn;
this.vind = vind;
this.temperatur = temperatur;
}
// set up stations array
const weatherStations = [];
// get action and display elements
const addStation = document.querySelector('.add-station');
const container = document.querySelector('.data-holder');
// set event listener
addStation.addEventListener('click', e => {
e.preventDefault();
// text input
const stationInput = document.querySelector('.station-name');
if (stationInput.value.length === 0) { return }
// create new station object and add to stations group
weatherStations.push(new WeatherStation(stationInput.value));
// render it all out
container.innerHTML = '';
const listItems = weatherStations
.map(station => `<li>${station.name}</li>`)
.join('');
container.innerHTML = listItems;
stationInput.value = '';
});
<section>
<article>
<input type="text" class="station-name" />
<button class="add-station">Add</button>
</article>
<article>
<ul class="data-holder"></ul>
</article>
</section>