简体   繁体   中英

How to pass firebase value/key as parameter in functions javascript

Is it possible to pass the key of where the data is located as a parameter in function?

For example;

function myfirebasedata(myDivTag, value){
  var ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
  ref.on('child_added', function(snapshot) {
    var data = snapshot.val();    
    myDivTag.innerHTML = data.value.age;
  });    
}

and then I could call this like:

myfirebasedata(divTagAgeJames, James);
myfirebasedata(divTagAgeBob, Bob);
....
....

So for example, when the first instance of the function is run/called myfirebasedata(divTagAgeJames, James);

it should replace the keywords in the reference of firebase code above to;

var ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
ref.on('child_added', function(snapshot) {
  var data = snapshot.val();    
  myDivTagJames.innerHTML = data.James.age;
});

Update:

在此处输入图片说明

You could try one of those:

1. snapshot.child()

ref.on('child_added', function(snapshot) {
    var age = snapshot.child(value).val().age;    
    myDivTag.innerHTML = age;
});

2. bracket notation

ref.on('child_added', function(snapshot) {
    var data = snapshot.val();    
    myDivTagJames.innerHTML = data[value].age;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM