使用 jQuery 事件跟踪多个变量时使用当前变量

Using the current variable when tracking multiple variables with jQuery event

下面是我正在使用的代码的简化示例以及我正在努力完成的工作。
我正在使用 jQuery 跟踪多个需要在特定事件上调用函数的变量。问题是我无法只使用刚刚更改的那个变量。

在 HTML 正文部分,我有几个输入字段,人们可以在其中填写数字。该数字应使用逗号作为千位分隔符进行格式化。感谢 Elias Zamaria,我为此找到了一个很好的解决方案 ()。现在我想用 jQuery 实现它,这样我就可以跟踪我所有的变量,这些变量将立即获得数字输入。

<html>
  <title></title>
  <head>

在 html 的头部,我插入我的脚本来跟踪我的变量:

    <script language="javascript">
      var Currency = function() {  
        this.currencyType = $("#businessAuthorisation, #businessIncome, #entityIncome, #entityAuthorisation);  

格式化数字并且应该只从正在更改的当前变量中获取当前数字的函数:

          this.formatCurrency = function(x) {
              var parts = x.toString().split(".");
              parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
              return parts.join(".");
          };
      };

跟踪开始,在 keyUp 事件上我的函数被调用。只有当前变量应该是被调用函数的参数。

      $(document).ready(function() {
        var currency = new Currency();
        currency.currencyType.keyup(function() {
          currency.formatCurrency(this);
        });
      });
    </script>
  </head>

以下是我表单中的相关输入字段:

  <body>
    <form>
      <table>
        <tr>
          <td><input type="number" name="entityAuthorisation" id="entityAuthorisation" value="<%=entityAuthorisation%>></td>
        </tr>       
        <tr>
          <td><input type="number" name="businessAuthorisation" id="businessAuthorisation" value="<%=businessAuthorisation%>"></td>
        </tr>
        <tr>
          <td><input type="number" name="entityIncome" id="entityIncome" value="<%=entityIncome%>"></td>
        </tr>       
        <tr>
          <td><input type="number" name="businessIncome" id="businessIncome" value="<%=businessIncome%>"></td>
        </tr>
      </table>
    </form>
  </body>
</html>

如何确保函数仅适用于引发事件的当前元素?

在 jQuery 事件处理程序中,this 指的是触发事件的元素。并且您需要使用 .value 来获取输入的值。所以你应该写:

  $(document).ready(function() {
    var currency = new Currency();
    currency.currencyType.keyup(function() {
      this.value = currency.formatCurrency(this.value);
    });
  });