【问题标题】:Click event oop点击事件oop
【发布时间】:2017-09-26 07:43:06
【问题描述】:

我想创建一个点击事件。

但是controlCount()中console.log的值不一样。

function Spinbox() {
  this.MIN_COUNT = 180;
  this.MAX_COUNT = 220;
  this.$inputBox = $(`<input type="text"/>`);
  this.$increaseButton = $(`<button type="button">+</button>`);
  this.$decreaseButton = $(`<button type="button">-</button>`);
}

Spinbox.prototype.controlCount = function() {
  console.log(this.$inputBox.val());
  // not working. because this = <button type="button">+</button>
  
}

Spinbox.prototype.create = function() {
  this.$increaseButton.click(this.controlCount);
  $("#wrap").append(this.$inputBox);
  $("#wrap").append(this.$increaseButton);
  $("#wrap").append(this.$decreaseButton);
}
var spinbox1 = new Spinbox();
spinbox1.create();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="wrap">

</div>

【问题讨论】:

  • 你为什么要获取按钮的val?你想要按钮的text 吗? this.$increaseButton.text()?那只会给你+符号。
  • 对不起,我的错误。我修改了我的问题

标签: javascript jquery oop


【解决方案1】:

您的问题是因为在点击处理程序的范围内,即。您的 controlCount() 函数,this 将引用单击的按钮,不是您的 Spinbox()

要解决此问题,您可以将this 直接转换为 jQuery 对象。但是,请注意,这两个按钮都没有value 属性。大概这是一个疏忽,所以我在这个例子中添加了它:

function Spinbox() {
  this.MIN_COUNT = 180;
  this.MAX_COUNT = 220;
  this.$inputBox = $(`<input type="text"/>`);
  this.$increaseButton = $(`<button type="button" value="increase">+</button>`);
  this.$decreaseButton = $(`<button type="button" value="decrease">-</button>`);
}

Spinbox.prototype.controlCount = function() {
  console.log($(this).val());
}

Spinbox.prototype.create = function() {
  this.$increaseButton.click(this.controlCount);
  $("#wrap").append(this.$inputBox);
  $("#wrap").append(this.$increaseButton);
  $("#wrap").append(this.$decreaseButton);
}
var spinbox1 = new Spinbox();
spinbox1.create();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="wrap"></div>

【讨论】:

    【解决方案2】:

    最简单的解决方案是在分配“点击”事件时使用jQuery.proxy() helper:

    this.$increaseButton.click($.proxy(this.controlCount, this));
    

    https://api.jquery.com/jQuery.proxy/ 中阅读有关jQuery.proxy 的更多信息。它将使用您的Spinbox 对象作为this 调用该方法。

    【讨论】:

      猜你喜欢
      • 2012-09-22
      • 1970-01-01
      • 2012-05-17
      • 2023-03-27
      • 1970-01-01
      • 2012-12-07
      • 2012-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多