MeteorJS 表单提交正在刷新启用了 event.preventDefault() 的页面
Posted
技术标签:
【中文标题】MeteorJS 表单提交正在刷新启用了 event.preventDefault() 的页面【英文标题】:MeteorJS form submission is refreshing the page with event.preventDefault() enabled 【发布时间】:2022-01-10 17:48:18 【问题描述】:约会应用程序是使用 MeteorJS 构建的,每当我尝试提交此表单以注册用户时,页面都会刷新。此外,Meteor.user().services.twitter.profile_image_url 似乎没有获得 Twitter 图像。请帮忙
imports/ui/components/partials/register-user.html
<template name="registerUser">
<div class="user-card">
<form id="user-form">
<div class="row">
<label for="gender">gender</label>
<select id="gender">
<option value="cis man">cis man</option>
<option value="cis woman">cis woman</option>
<option value="non binary" selected>non binary</option>
<option value="trans man">trans man</option>
<option value="trans woman">trans woman</option>
</select>
</div>
<div class="row">
<label for="prefer">seeking</label>
<select id="prefer">
<option value="cis men">cis men</option>
<option value="cis women">cis women</option>
<option value="everyone" selected>everyone</option>
<option value="non binary">non binary</option>
<option value="trans women">trans women</option>
<option value="trans men">trans men</option>
</select>
</div>
<div class="row">
<button class="button-primary register-user" type="submit" form="user-form">register</button>
</div>
</form>
</div>
</template>
imports/ui/components/partials/register-user.js
import Meteor from 'meteor/meteor';
import Session from 'meteor/session';
import './register-user.html';
Template.registerUser.onCreated(function ()
this.register_name = Meteor.user().profile.name;
this.register_img = Meteor.user().services.twitter.profile_image_url;
);
Template.registerUser.events(
'submit .register-user' (event)
event.preventDefault();
var gender = event.target.gender.value;
var prefer = event.target.prefer.value;
if (confirm("by continuing you verify you are a minimum of 21 years old"))
Meteor.call('register.user', this.register_name, "", gender, prefer, (error) =>
if (error)
Flash.danger(error.error, 3000);
else
Session.set('complete': true);
);
,
);
imports/api/methods.js
...
'register.user': function(name, img, gender, prefer)
RegisteredUsers.insert( _id: this.userId, complete: true, role: false );
Profiles.insert(
_id: this.userId, name: name, img: img, gender: gender, prefer: prefer, address: "", right: [], matches: [],
);
// redisCollection.hset(this.userId, "name": name, "img": img, "gender": gender );
,
...
【问题讨论】:
【参考方案1】:您的示例显示事件映射错误:
'submit .register-user' (event)
您使用了按钮的类映射,但提交事件来自表单。然后改成:
'submit #user-form' (event)
【讨论】:
【参考方案2】:我认为问题在于您将 submit 事件映射到具有类 register-user 的按钮。尝试更改您的代码以引用 submit 事件来自的表单。您可以使用其 id (user-form) 来执行此操作。
应该是这样的:
'submit #user-form'(event)
event.preventDefault();
...
【讨论】:
以上是关于MeteorJS 表单提交正在刷新启用了 event.preventDefault() 的页面的主要内容,如果未能解决你的问题,请参考以下文章