我上了一堂 JavaScript 课。在本类(class)中,我有一个方法检查文本字段的输入。当html文档的正文加载时,我想第一次调用这个方法。之后,我想使用“onchange()”事件。
//##############
//# Javascript #
//##############
class NoteController{
constructor() {
this.store = new NoteStore(); // instance of a dataStore
}
HandleInputFields(){ // Enable / Disable a button by validation
var input = document.getElementById('edtNoteTitle').value; // Get the input text from the field
var inputIsValid = true;
if(input.length < 1) // text is empty
inputIsValid = false;
else if (this.store.notes.some(n => n.title === input)) // check for duplicates in the store
inputIsValid = false;
document.getElementById('btnCreateNote').disabled = !inputIsValid; // disable the button or keep it enabled
}
}
//########
//# HTML #
//########
<body onload="HandleInputFields()"> // Disable the button when loading the Document
<input type="text" id="edtNoteTitle" onchange="HandleInputFields()"> // Validate the Input field
</body>
因此,当我打开文档时,它显示“HandleInputFields()”未定义。如何正确调用这个方法?
最佳答案
您需要将该方法定义为静态
方法,并通过其类
范围访问它。
所以在class NoteController { ...
将 HandleInputFields() {
更改为 static HandleInputFields() {
然后通过
<body onload="NoteController.HandleInputFields()">
说明:当前您正在尝试访问没有上下文的方法,该方法会回退到 window.HandleInputFields()
。然而,您的意图是通过 NoteController
的上下文访问它,因此调用 NoteController.HandleInputFields()
。但是,为了能够直接在类上而不是在实例上进行调用,您需要将其定义为 static .
关于javascript - 调用 JavaScript 类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43226187/