我正在从我的firebase数据库中读取很多不同的数据,目前,我已对其进行了硬编码。这工作正常,但是我有很多代码行,现在当我想改变我的代码时,它变得非常混乱。下面我已经粘贴了我当前的装备。
var ref = new Firebase("URL");
// Data set 1
ref.on('child_added', function(snapshot) {
var snapshot = snapshot.val();
textbox1.innerHTML = snapshot.getvalue1.age;
});
ref.on('child_changed', function(snapshot) {
var snapshot = snapshot.val();
textbox1.innerHTML = snapshot.getvalue1.age;
});
// Data set 2
ref.on('child_added', function(snapshot) {
var snapshot = snapshot.val();
textbox2.innerHTML = snapshot.getvalue2.age;
});
ref.on('child_changed', function(snapshot) {
var snapshot = snapshot.val();
textbox2.innerHTML = snapshot.getvalue2.age;
});
..... ..... .....
// Data set 100
ref.on('child_added', function(snapshot) {
var snapshot = snapshot.val();
textbox100.innerHTML = snapshot.getvalue100.age;
});
ref.on('child_changed', function(snapshot) {
var snapshot = snapshot.val();
textbox100.innerHTML = snapshot.getvalue100.age;
});
而不是我采用的方法,是否可以使用for循环或类似的东西循环遍历每个数据,因为我的firebase中每个textbox / keyword的结构或多或少相同。
我对javascript相当新,但是根据我对java的了解,我相信它会从这样的东西开始;
var myTextbox = document.getElementById("mytextbox");
for (var i = 0; i < myTextbox.length; i++) {
}
欢迎任何帮助,如果我的问题不明确,请告诉我。
编辑:
Mydata:
textbox1 - value - age : "This is textbox 1, age:21"
textbox2 - value - age : "This is textbox 2, age:53"
textbox2 - value - age : "This is textbox 3, age:04"
....
....
答案 0 :(得分:0)
我不是firebase的专家,但这里有一些你可以尝试的潜在解决方案。例如,您可以使用'value'代替编写child_added和child_changed。 (Reference)
ref.on('value', function(snapshot) {
var snapshot = snapshot.val();
textbox1.innerHTML = snapshot.getvalue1.age;
});
但是这不是一个很好的解决方案,因为您希望一次检索所有值。 看来你的快照的所有值都带有attributes'getValuei',其中i来自1 ... n。 一个更好的解决方案可能是这样的..
ref.on('value', function(snapshot) {
var snapshot = snapshot.val();
textbox1.innerHTML = snapshot.getvalue1.age;
textbox2.innerHTML = snapshot.getvalue2.age;
textbox3.innerHTML = snapshot.getvalue3.age; //..and so on..
});