jQuery .change(function)无法调用类函数

时间:2018-12-08 14:24:15

标签: javascript jquery

我正在使用jQuery在JavaScript中创建一个验证脚本,并且正在使用jQuery中的.change()函数,当输入值更改时,我希望它从自身调用对象函数displayError()。在构造子类时会调用该函数。

课程:

class Input { //this makes a class that all inputs should be assigned to
  constructor(input, error) {
    this.inputBox = input; //jQuery Object of the input box
    this.errorText = error; //jQuery Object of the error text
    this.required = this.inputBox.prop("required"); //return true if the inputBox has attribute required and false if not
    this.unique = this.inputBox.prop("data-unique"); //USED FOR KNOWING IF NEEDED TO QUERY IN DATABASE
    this.errorText.hide(); //hides the error text
  }

  displayError() { //function that will decide whether the error text needs displaying
    var valid = this.auth(); //sees if the value of the input box is valid
    //QUERY DB TO SEE IF TAKEN
    if (!valid) {
      this.errorText.show(); //shows the error text
    }
    //else if TAKEN && this.unique{SHOW DIFFERENT MESSAGE}
    else { //runs if the value is valid
      this.errorText.hide(); //hides the error text
    }
  }

  auth() {
    let value = this.inputBox.val(); //asssigns the value of the input box to 'value'
    if ((!this.required && value == "") || this.isValid(value)) { //if not required the value can be nothing, but if it is required then the value must be validated
      return true; //says the value is valid
    } else {
      return false;
    } //says the value is not valid
  }

  liveErrors() {
    this.inputBox.change(function() {
      this.displayError()
    }); // <--- ISSUE HERE
  }
}

我所有的类变量都已设置并且正在运行,我不确定是否是因为在.change()之后,我在未设置的函数中引用了该变量,因为它不是全局变量,如果那是这个问题我不确定如何克服。

我对JavaScript和OOP还是陌生的,如果我有任何不正确的术语或做过一些愚蠢的事,对不起,谢谢。

1 个答案:

答案 0 :(得分:0)

在用作this.inputBox.change的回调的匿名内部函数中,this是元素this.inputBox指向的元素,它是dom中的输入元素。您可以在尝试调用console.log( this, typeof this );

之前通过在该函数中调用this.displayError();进行验证

您可以使用jQuery.proxy在所选上下文this中调用成员函数。

我精简了代码并使用了keypress而不是示例代码段的更改,但是您可以看到它可以通过在两个输入字段中键入并看到它们触发对特定于实例的成员元素的更改来触发实例方法

在您的成员函数中,this应该可以正常工作。

class Input { //this makes a class that all inputs should be assigned to

  constructor(input, error) {
    this.inputBox = input; //jQuery Object of the input box
    this.errorText = error; //jQuery Object of the error text
  }

  toggleError() { //function that will decide whether the error text needs displaying
    this.errorText.toggle(); //hides the error text
  }

  liveErrors() {
    this.inputBox.keypress($.proxy(this, 'toggleError'));
  }
}

let first = new Input($('.first-input'), $('.first-error'));
let second = new Input($('.second-input'), $('.second-error'));

first.liveErrors();
second.liveErrors();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="first-input">
<span class="first-error">First!</span>
<br/>
<input class="second-input">
<span class="second-error">Second!</span>