gpt4 book ai didi

javascript - 为什么控制台.log 不起作用并刷新页面?

转载 作者:行者123 更新时间:2023-11-28 17:49:59 30 4
gpt4 key购买 nike

我正在编写一个 JS 文件来处理 HTMl 页面中的客户端事件。 注册表就是这些事件之一,因此用户输入他的姓名和密码,当单击提交按钮时,JS文件必须处理该事件。

var registerForm = document.getElementsByClassName('register-form');
registerForm[0].addEventListener('submit',function(e) {
var username = document.getElementsByClassName('register-form-username')[0].value;
var userpass = document.getElementsByClassName('register-form-pass')[0].value;
var userDetails={
name : username,
pass: userpass
};

console.log(JSON.stringify(userDetails)); /*this is working and it print out on the console the same name and pass the user entered*/
globalvar.register(userDetails);

});

var globalvar= {
register : function(userDetails) {
console.log(JSON.stringify(userDetails)); //this does not print in the console and it refreshes the page and reset the form fields
var x={
comment : "",
userDetails: {
name : userDetails.name ,
email : userDetails.pass
}
};
console.log(JSON.stringify(x));
localStorage.setItem('localStor' , JSON.stringify(x));
}
};

我错过了什么?

最佳答案

如果您想禁用提交的默认行为(这会导致页面刷新),您将需要使用 Event 对象的 preventDefault() 方法:

registerForm[0].addEventListener('submit',function(e) {
e.preventDefault()
...
});

关于javascript - 为什么控制台.log 不起作用并刷新页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45772595/

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