Javascript+Firebase博客addpost函数firstId返回undefined



我正在用Js和Firebase创建一个博客。当我将帖子添加到firebase数据库时,第一个帖子的Id是undefined,然后in从myid-0开始增加。这是我的代码:

<button onclick="writeUserData(document.getElementById('blog-title').value, document.getElementById('blog-content').value, uniqueId(uniqueId))">Add</button>

function uniqueId(uniqueId) {
var counter = 0;
window.uniqueId = function(){
return ('myid-' + counter++);
}
}
function writeUserData(title, content, postID) {
firebase.database().ref('posts/' + postID).set({
title: title,
content: content
});
}

为什么它没有开始添加myid-0的帖子?

这是因为函数uniqueId()不正确。你可以通过在你的页面上有一个带有以下代码的按钮来看到它:

<input
id="clickMe"
type="button"
value="clickme"
onclick="console.log(uniqueId());"
/>

因此,如果你将你的功能更改为以下内容,它就会起作用:

var counter = 0;
function uniqueId() {
return 'myid-' + counter++;
}
function writeUserData(title, content, postID) {
firebase.database().ref('posts/' + postID).set({
title: title,
content: content
});
}

<button onclick="writeUserData(document.getElementById('blog-title').value, document.getElementById('blog-content').value, uniqueId())">Add</button>

请注意,您可以让Firebase生成UniqueId,请参阅https://firebase.google.com/docs/reference/js/firebase.database.Reference#push

最新更新