是否可以从 HTML 事件中的类调用方法,例如"onblur"?



我有个小问题解决不了…

我通常这样检查我的表单:

function checkFirst(field) {
if (field.value.length < 2 || !regLetters.test(field.value)) {
//do something
} else {
//do something else
firstNameOk = true;
}
}

和在HTML一侧的onblur="checkFirst(this)".

现在我正在使用OOP,我不能在onblur中使用我的方法,我不知道如何在onblur HTML属性中调用类…

我已经有了一个解决方案来解决这个问题,而不是在HTML中使用onblur,在我的情况下,我想知道它是否可能。

有人来帮我吗?编辑:为了避免人们告诉我使用addEventlistener,我向你展示了我的解决方案,工作得很好,但不是我想使用的…

this.data.forEach(item => item.addEventListener('blur', function () {
console.log(item.id)
// check first name field // 
if (item.id === "first") {
if (item.value.length < 2 || !this.regLetters.test(item.value)) { // if this field length =
this.highlightField(item, true);
} else {
this.highlightField(item, false);
this.errorMessagesReset(item);
this.firstNameOk = true;
}
// check last name field // 
} else if (item.id === "last") {
if (item.value.length < 2 || !this.regLetters.test(item.value)) {
this.highlightField(item, true);
} else {
this.highlightField(item, false);
this.errorMessagesReset(item);
this.lastNameOk = true;
}
// check email field // 
} else if (item.id === "email") {
if (item.value.length < 2 || !this.regmail.test(item.value)) {
this.highlightField(item, true);
} else {
this.highlightField(item, false);
this.errorMessagesReset(item);
this.emailOk = true;
}
// check textarea field // 
} else if (item.id === "message") {
if (item.value.length < 1 || item.value > 100) { // if length of item is sup or equal to 1 and 
this.highlightField(item, true);
} else {
this.highlightField(item, false);
this.errorMessagesReset(item);
this.messageOk = true;
}
}
}.bind(this))); ```

应该是属于这个类的静态函数。这样你就可以直接调用它。

最新更新