我想创建一个点击事件。
但是,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>
答案 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
。