如果它在函数内部,为什么不运行此代码?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如果它在函数内部,为什么不运行此代码?相关的知识,希望对你有一定的参考价值。
这是我的代码确实有效:
firebase.initializeApp({});
var auth = firebase.auth();
const firestore = firebase.firestore();
const settings = {timestampsInSnapshots: true};
firestore.settings(settings);
var db = firebase.firestore();
$(function() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var uid = user.uid;
// code in question
db.collection('users').doc(uid).collection('people').doc().set({
firstname: "John",
lastname: "Doe"
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
} else {
// User is signed out.
}
});
});
但是,我希望在提交页面上的表单后触发db.collection
位;这样的事情:
firebase.initializeApp({});
var auth = firebase.auth();
const firestore = firebase.firestore();
const settings = {timestampsInSnapshots: true};
firestore.settings(settings);
var db = firebase.firestore();
$(function() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var uid = user.uid;
$('#myform').on('submit', function() {
db.collection('users').doc(uid).collection('people').doc().set({
firstname: "John",
lastname: "Doe"
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
});
} else {
// User is signed out.
}
});
});
但无论出于何种原因,这都行不通。
编辑:这是整个#myform
。这存在于bootstrap模式中
<form id="myform">
<div class="form-row">
<div class="col-md-12">
<label for="firstname">First Name</label>
<div class="input-group">
<span class="input-group-addon"><i class="icofont icofont-user"></i></span>
<input type="text" class="form-control" id="firstname" required>
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-12">
<label for="lastname">Last Name</label>
<div class="input-group">
<span class="input-group-addon"><i class="icofont icofont-user"></i></span>
<input type="text" class="form-control" id="lastname" required>
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-12">
<label for="email">Email</label>
<div class="input-group">
<span class="input-group-addon"><i class="icofont icofont-email"></i></span>
<input type="email" class="form-control" id="email" required>
</div>
<div id="email-error"></div>
</div>
</div>
<div class="form-row">
<div class="col-md-12 mb-3">
<label for="phone">Phone</label>
<div class="input-group">
<span class="input-group-addon"><i class="icofont icofont-phone"></i></span>
<input type="tel" class="form-control" id="phone">
</div>
<div id="phone-error"></div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="btn-add-person">Add Person</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</form>
答案
您的表单提交可能正在重新加载页面。尝试在你的onsubmit="return false;"
的帽子里贴上<form>
。
以上是关于如果它在函数内部,为什么不运行此代码?的主要内容,如果未能解决你的问题,请参考以下文章