简体   繁体   English

使用jQuery从Firebase更新页面上的数据时遇到问题

[英]Trouble updating data on page from Firebase with jquery

  //Display User in header
  usersRef.child(uid).on('value', function(name){
    var dName = (name.val().displayName);
    $("#userName").replaceWith("<li id=userName><span>Logged in as " + dName + "</span></li>");
    //Get the first Letter of the users name
    firstLetter = dName.charAt(0);
    //Display icon in header
      console.log("User Image Replaced");
      $("#userImage").replaceWith("<li id='userImage'>" + firstLetter + "</li>");
  });

The above code successfully creates a user icon in the header of my website. 上面的代码成功在我的网站标题中创建了一个用户图标。 It is the first letter of their name with a background the color of their 'user color'. 这是他们名字的第一个字母,其背景颜色为“用户颜色”。 When their 'user color' gets changed I want the icon in the header to update. 当他们的“用户颜色”更改时,我希望标题中的图标更新。

I have been getting mixed results, but usually it would update the first time I change the color and I would have to click around the page for it to do it again. 我得到的结果好坏参半,但是通常它会在我第一次更改颜色时更新,因此我必须单击页面周围的颜色才能再次执行。 But not always, sometimes it would not work the first time and sometimes it would work the first three times. 但并非总是如此,有时它不会第一次起作用,有时它会前三遍起作用。

Have I coded it in a way which is causing this problem or is it a Firebase thing? 我是否以导致此问题的方式对其进行编码,或者这是Firebase的事情?

You need to add child_changed event for the firebase reference URL. 您需要为child_changed参考URL添加child_changed事件。

Following is the example: 以下是示例:

usersRef.on("child_changed", function(snapshot) {    
      document.getElementById("username").innerHTML = udata.name;
      document.getElementById("username").style.backgroundColor=udata.color;
});

Sample fiddle: http://jsfiddle.net/learningloop/ha5wncmx/19/ 小提琴示例: http : //jsfiddle.net/learningloop/ha5wncmx/19/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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