javascript - 我的 javascript 类的自定义对象实验室无法正常运行
问题描述
我正在为我的 Javascript 类开发一个实验室,它是一个致力于自定义对象和构造函数的实验室。目的。我正在制作我喜欢的一些音乐艺术家的自定义对象。创建我可以重复访问的收藏夹列表。我创建了一个创建音乐艺术家的构造函数(称为 musicArtist)。传递参数,然后将自定义对象存储在数组中。然后我创建了另一个名为 showInfo() 的函数。在第一行,我输入了以下代码:
变量信息 = “”</p>
这会创建一个空字符串,我可以在遍历对象时向其中添加信息。然后我创建了一个 for 循环,其中有一个名为 count 的计数变量设置为 0。在 forloop 中,我将有关对象的详细信息添加到 info 变量中。当用户单击按钮时,它应该运行 showInfo() 函数但它没有?这是我的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<title> Custom Objects Lab</title>
<script>
function musicalArtist(name, song, description){
this.name = name;
this.song = song;
this.description = description;
}
var t= new musicalArtist("Tyler the Creator", "All of them", "He's
beautiful I might cry");
var s= new musicalArtist("Slipknot", "Wait and Bleed", "Literally so
awesome");
var a= new musicalArtist("Ayesha Erotica", "Literal Legend", "She is
such an icon");
var myArtists = [t];
var myAritsts= [s];
var myAritsts = [a];
function showInfo() {
var info = ""
for (var count = 0; count < 3; count++) {
info += "Name:" + myAritsts[count].name + "\n";
info += "Best Song:" + myAritsts[count].song + "\n";
info += "Descrition:" + myAritsts[count].description +
"\n";
}
alert(info);
}
</script>
</head>
<body>
<button onclick="showInfo()">A</button>
</body>
</html>
解决方案
在加载 javascript 时尝试使用事件绑定,并在 JS 底部添加以下代码:
document.getElementById("button").addEventListener("click", showInfo);
将按钮的 HTML 更改为:
<button id="button">A</button>
您的 console.log 中发生错误,因为代码不正确,但现在它确实加载了 click 事件
推荐阅读
- git - 使用 git filter-repo 将子目录移动到根目录,同时将文件保留在根目录中
- php - 如何防止执行查询重新加载页面。我试过 preventDefault(); 它有效,但它阻止了 php 的执行
- r - R ggmcmc 格式化跟踪图
- java - 无法解析符号“BottomSheetDialog”
- c# - 如何使用 ssis 脚本任务将文件从本地文件夹复制到在线共享点
- html - 如何在大 div 中居中更多 div
- python - Django 似乎从全局安装导入包,而不是从我的虚拟环境(venv)
- r - 如何使用 fileInput 从上传到 Shiny 应用程序的 .xlsx 文件中获取工作表名称列表?
- javascript - Pollyjs 休息持久性没有捕捉到任何与 cypress 的请求
- sql - 姜戈 | 我想从数据库中删除一个产品及其所有相关数据