Class is not defined onClick event

人走茶凉 提交于 2021-02-10 16:11:57

问题


I use the new class syntax for JS. When I press a button, I want to call a method from a class. To archieve this, I set this method static.

class NoteController { // The controller class
    constructor() { // Initialization
        // ...
    }

    static CreateNote() { // The method to call - static
        // ....
    }
}




<!DOCTYPE html>
<html>

<head>

    // ....
    <script src="NoteController.js"></script> // Link the js file to the html file

</head>

<body>

    // ....
    <button type="button" id="btnCreateNote" onclick="NoteController.CreateNote()">Create</button> // call the method

</body>

</html>

When I click the button, it says, NoteController is not defined. I really do not get, what is wrong there.

A picture of my project folder:

Maybe this helps.


回答1:


EDIT: Correction to make it static:

<script>
class NoteController { // The controller class
    constructor() { // Initialization
        // ...
        alert('constructor called');
    }

    static CreateNote() { // The method to call - static
        // ....
        alert('create note');
    }
}
//var nc=new NoteController();
//console.log(nc);
</script>


<button type="button" id="btnCreateNote" onclick="NoteController.CreateNote()">Create</button> // call the method

JSFiddle

This is the working example of your code:

<script>
class NoteController { // The controller class
    constructor() { // Initialization
        // ...
        alert('constructor called');
    }

    CreateNote() { // The method to call - static
        // ....
        alert('create note');
    }
}
var nc=new NoteController();
console.log(nc);
</script>


<button type="button" id="btnCreateNote" onclick="nc.CreateNote()">Create</button> // call the method

Working JSFiddle




回答2:


Since lack of information about NoteController.js,I assume that your NoteController.js has below code.

    function NoteController()
    {
    //variables
    //sub functions
   function CreateNote()
     {
      //code
     }
    }

So now you need to create the object of the function and call it.

<script src="NoteController.js"></script>
<script>
var _noteController=new NoteController();
</script>

<body>
    <button type="button" id="btnCreateNote" 
onclick="_noteController.CreateNote()">Create</button> 
</body>



回答3:


Include your class inside the <script> tags, So that the browser will identify the javascript code and execute it!



来源:https://stackoverflow.com/questions/43231123/class-is-not-defined-onclick-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!