实时点击/链接计数器 [英] Real Time Click/link counter

查看:65
本文介绍了实时点击/链接计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码...

<script>
      $(document).ready(function(){
    var x = 0;    
    function resetcounter() {
    x = 0;
    document.getElementById("counting").value = x;
    }

   function count() {
   if(x<50)
    {
      x += 1;
    }
    else
    {
        x=0;
    }
    document.getElementById("counting").value = x;
   }
   $('#btn').click(

         function() {
         count();
    });

    $('#reset').click(

    function() {
           resetcounter();
    });  
});
</script>

效果很好.但是我需要它实时更新.我想使用firebase.我如何将提要添加到Firebase中.基本上我需要这个...每次有人单击我网站上的某个按钮时,计数器就会跟踪它被单击了多少次,并实时显示在页面上.

it works great. i need it however to update in real time. i would like to use firebase. How do i get the feed into firebase. basically i need this...everytime someone clicks a certain button on my site, there is counter keeping track how many times it has been clicked and it is shown to everyone on the page in real time.

推荐答案

此处的一般方法是将"x"变量移到Firebase并使用它来支持计数器的状态.由于我们要对多个潜在客户进行计数,因此我们将这些更新与事务合并在一起.

The general approach here is to move your 'x' variable out to Firebase and use that to back the state for the counter. Since we're doing a count across multiple potential clients, we wrap those updates with a transaction.

它看起来像这样:

var x = new Firebase('https://countingex.firebaseio-demo.com/');

x.on('value', function f(s) {
    $('#counting').text(0 + s.val());
});

$('#btn').click(function() {
  x.transaction(function(current_value) {
    return current_value + 1;
  });
});

$('#reset').click(function() {
    x.set(0);
});

我在JSFiddle上放置了工作示例;通过在多个窗口中打开它来看看.为了简单起见,我省略了针对魔术数字50的条件.

I've put a working example up on JSFiddle; take a look by opening it in multiple windows. I left out the conditional against the magic number 50 for the sake of simplicity.

要开始使用Firebase的其他基础知识,我建议您看一下我们的互动教程.

To get started with other Firebase basics, I would recommend you take a look at our interactive tutorial.

这篇关于实时点击/链接计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆