【发布时间】:2021-10-22 06:23:58
【问题描述】:
我正在编写一个代码,用户输入信息并将其存储在一个对象中,但是当我通过警告它的一个值来检查对象是否被保存时,它说没有这样的对象。 这是我的代码。
let users = {};
function user(name,real){
this.username = name,
this.realname = real,
this.id = Math.floor(Math.random() *1000);
this.subs = 0,
this.videos = [],
this.listuser = function() {
return this.username;
}
};
function newuser(name, email,username){
users[name] = new user(username, name);
};
let savefile = () => {
var channame = string(document.getElementById('channame'));
var name = string(document.getElementById('name'));
var email = string(document.getElementById('email'));
newuser(name,email,channame);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>youtube ripoff</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<br> <br><br><br><br><br>
<form action="">
<label for="username">Channel Name: </label>
<input type="text" id="channame" name="channelname"><br>
Real Name
<input type="text" id="name" name="name"><br>
Email
<input type="text" id="email" name="email"><br>
<input type="submit" value="Submit" onmousedown="newuser('name1','name@gmail.com','channelname1');">
<br><br><br><br>
<input type="button" value="Load Channels" id="seech" name="seechannels" onmousedown="alert(users['name1'].listuser());"><br>
</form>
<script src="script.js">
function fun(){
window.alert("starting program...")
//other code
}
</script>
</body>
</html>
是否有某种我没有看到的错误?
【问题讨论】:
-
当你使用
<script src="…">时,它的内容会被忽略。见What does a script-Tag with src AND content mean?。像onclick这样的内联事件处理程序是not recommended。它们是一种obsolete, hard-to-maintain and unintuitive 注册事件的方式。总是useaddEventListener。使用browser console (dev tools)(点击F12)并阅读任何错误。 -
this里面的listuser函数不是你想象的那样。可能未定义,因为它是从 mousedown 处理程序调用的。
标签: javascript html object