gpt4 book ai didi

javascript - LocalStorage 变量是否存在 : if statement does not work after element reloading (page is reloading after submiting reloaded form)

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:13:49 26 4
gpt4 key购买 nike

请帮助修复算法并防止点击提交后重新加载:我的网站必须检查,用户是否曾经输入过昵称。如果他有,那么网站必须显示他的名字,如果没有,则要求输入。如果用户决定更改它,他将单击“重置用户名”。

点击“重置”后,用户必须提交两次他的名字(第一次点击“设置”后,整个页面重新加载,第二次点击后,它只重新加载一个元素)。请帮助修复它 - 用户只需提交一次。

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var formNewName = '<form id="new-task"> <input id="nickN" autocomplete="off" autofocus placeholder="Write your nick" type="text"> <input id="submitname" type="submit" value="Set new name1"> </form>';
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#setnewname').onsubmit = () => {
var newname;
localStorage.setItem('localN', newname);
document.querySelector('#nickName').innerHTML = formNewName;
// Stop form from submitting
return false;
};
});
// Checking does user entered his name
if ( !localStorage.getItem('localN') || localStorage.getItem('localN')=="undefined" )
{ var nick;
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#nickName').innerHTML = formNewName;
document.querySelector('#new-task').onsubmit = () => {
nick = document.querySelector('#nickN').value;
localStorage.setItem('localN', nick);
document.querySelector('#nickName').innerHTML = "Your nick is: <b>" + localStorage.getItem('localN') + '</b>';
// Stop form from submitting
return false;
};
});
}
else
{
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#nickName').innerHTML = "Your nick is: <b>" + localStorage.getItem('localN') + '</b>';
});
}
</script>
</head>
<body>
<div id = "nickName"></div>
<div id = "newname">
<br>
<form id="setnewname">
<input id="submitreset" type="submit" value="Reset nick name">
</form>
</div>
</body>

更新:event.preventDefault();event.stopPropagation();对解决问题没有帮助。

最佳答案

很抱歉迟到回复,如果你仍然有它,我看不到你在代码中从用户那里获取值的地方没有用户可以输入的输入字段所以我会添加它然后在 id submitreset 你会这样做:我最常使用 jquery,所以它的语法是

// HTML CODE TO ADD
<input type="text" name="entername" id="entername">

// than in jquery for the submit button you already have
$(document).on("click","#submitreset",function(e){
e.preventDefaults();
var name = $(this).val();

// you can print the value in the div with this id
$("#nickName").html(name);


});

关于javascript - LocalStorage 变量是否存在 : if statement does not work after element reloading (page is reloading after submiting reloaded form),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53077537/

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