gpt4 book ai didi

jquery - 从 jQuery 函数返回值

转载 作者:行者123 更新时间:2023-12-01 07:10:14 30 4
gpt4 key购买 nike

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

 $(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>

任何形式的帮助将不胜感激。

最佳答案

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)
});
}

关于jquery - 从 jQuery 函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29193334/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com