点击活动oop

时间:2017-09-26 07:43:06

标签: javascript jquery oop

我想创建一个点击事件。

但是,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>

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

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

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

详细了解https://api.jquery.com/jQuery.proxy/中的jQuery.proxy。它会将您Spinbox对象的方法称为this