首页 > 解决方案 > 我的 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>

标签: javascriptarrayscustom-object

解决方案


在加载 javascript 时尝试使用事件绑定,并在 JS 底部添加以下代码: document.getElementById("button").addEventListener("click", showInfo);

将按钮的 HTML 更改为: <button id="button">A</button>

您的 console.log 中发生错误,因为代码不正确,但现在它确实加载了 click 事件


推荐阅读