【问题标题】:Returning value from a jQuery function [duplicate]从jQuery函数返回值[重复]
【发布时间】:2015-05-25 10:40:11
【问题描述】:

我想知道为什么这个 jQuery 函数没有从函数返回任何值。它确实增加了 Firebase 中的值,除了返回值之外,其他一切都可以正常工作。严重坚持了几个小时:(

 $(function(){
  $('.post').each(function(){
    var $this = $(this);
    var postTitle = $this.find('.title').text();

    //create separate firebase reference
    var postRef = new Firebase('https://bloganalyzer-view-stat.firebaseio.com/trying/'+postTitle);

    var pData = getFirebaseData(postRef,'post');
    $this.find('.count').empty().html(pData);
  });
});

function getFirebaseData(r,bp){
  var data;
  r.once('value', function(snap) {
    data = snap.val();
    if (data == null) {data=1;}
    else if(bp=='blog') {data+=10;}
    else if(bp=='post') {data+=1;}
    r.set(data);
  });
  return data;
}

HTML 部分是这样的..

<div class="post">
  <span class="title">Title 1</span>
  <span class="viewCount"></span>
</div>
<div class="post">
  <span class="title">Title 2</span>
  <span class="viewCount"></span>
</div>

我们将不胜感激。

【问题讨论】:

    标签: jquery function firebase


    【解决方案1】:

    firebase api 是一个异步 api,所以你不能返回值 frrm 而是你可以使用回调来做处理

    $(function () {
        $('.post').each(function () {
            var $this = $(this);
            var postTitle = $this.find('.title').text();
    
            //create separate firebase reference
            var postRef = new Firebase('https://bloganalyzer-view-stat.firebaseio.com/trying/' + postTitle);
    
            //pass a callback to getFirebaseData which will be called once the request is completed
            getFirebaseData(postRef, 'post', function (pData) {
                //this will get called once the request is completed
                $this.find('.count').html(pData);
            });
        });
    });
    //accept the callback as the last param which is a function
    function getFirebaseData(r, bp, callback) {
        r.once('value', function (snap) {
            var data = snap.val();
            if (data == null) {
                data = 1;
            } else if (bp == 'blog') {
                data += 10;
            } else if (bp == 'post') {
                data += 1;
            }
            r.set(data);
            //once the value of data is calculated call the callback and pass the value to it instead of trying to return it
            callback(data)
        });
    }
    

    【讨论】:

    • 非常感谢先生..您几乎节省了我一天..真的很感激。再次感谢..
    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 2020-08-26
    • 2011-04-18
    • 2011-04-19
    • 1970-01-01
    相关资源
    最近更新 更多