2017-04-05 61 views
1

我使用JS的新类语法。当我按下按钮时,我想调用一个类的方法。为了实现这一点,我将此方法设置为静态。类未定义onClick事件

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> 

当我点击按钮,它说,NoteController没有定义。我真的不明白,那里有什么问题。

我的项目文件夹中的图片:

enter image description here

也许这会有所帮助。

+0

NoteController.js是否在您的HTML页面是相同的文件夹?你得到什么确切的错误?我敢打赌我的钱没有被加载到HTML页面上。 – ProgrammerV5

+0

我刚刚更新了我的照片:) – peterHasemann

+0

添加了一个响应和一个工作示例。没有像在你的结构中那样在文件中分开,但我希望它有助于理解你的工作代码中缺少什么。 – ProgrammerV5

回答

2

编辑: 修正,使之静:

<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

这是你的代码的工作示例:

<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 

工作JSFiddle

+0

该方法应该是静态的,调用时没有NoteController的实例。 –

+0

我的不好,用静态方法增加了一个新例子。 – ProgrammerV5

+0

我正在测试同样的事情,但如果您将JS代码移动到jsfiddle中的JS区域,它将停止工作,不知道为什么。检查[这个小提琴](https://jsfiddle.net/69b06hvj) –

1

由于缺乏有关NoteController.js的信息,我假设您的NoteController.js具有以下代码。

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

所以现在你需要创建函数的对象并调用它。

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

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

不,如上所述,这是一个完整的类:)它是一个相对较新的语法 – peterHasemann

+0

只要检查按钮元素,并检查什么是onclick的绑定?以及如何在html呈现的页面上定义NoteController。 –

1

将您的课程包含在<script>标记中,以便浏览器识别JavaScript代码并执行它!