2017-09-26 11 views
-1

clickイベントを作成したいと思います。Clickイベント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>

+1

なぜあなたはボタンの 'val'を取得しようとしていますか?ボタンの 'text'を使いますか? 'this。$ increaseButton.text()'?それはちょうどあなたに+シンボルを与えます。 – TKoL

+0

申し訳ありませんが、mymistake。私の質問を変更します –

答えて

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>

0

最も簡単な解決策は、あなたが「クリック」イベントを割り当てるときに、ラインにjQuery.proxy()ヘルパーを使用することです:

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

jQuery.proxyについては、https://api.jquery.com/jQuery.proxy/をご覧ください。 Spinboxオブジェクトのメソッドをthisと呼びます。

+0

ありがとうございます。よくやった! –