从原型函数内的函数增加this.clicks

时间:2017-04-19 18:17:02

标签: javascript prototype this

此代码显示两只猫以及每只猫被点击的次数,如何从Cat.prototype.clickInc()方法中增加每只猫的.clicks属性?

    $(document).ready(function() {
    var cats = [];

  var Cat = function(id, image_path) {

    this.id = id;
    this.image_path = image_path;
    this.clicks = 0;

};


 Cat.prototype.clickInc = function() {

  $('#'+this.id).click(function(){

     this.clicks++;

      return this.clicks;
   });
  };//use a closure here

var poly = new Cat("poly", "poly.jpg");
var chewie = new Cat("chewie", "chewie.jpg");
cats.push(poly);
cats.push(chewie);

for(i=0; i<cats.length; i++)
{    
    var catInfo = '<div class="cats"><div id="'+cats[i].id+'"><img src='+cats[i].image_path+'><h3>'+cats[i].id+'</h3></div><div class="clickNos"><span ="label">Number of clicks</span><span class="clicks">'+cats[i].clicks+'</span></div></div>';
    $("#container").append(catInfo);
    cats[i].clickInc();
}


});

1 个答案:

答案 0 :(得分:1)

{p} thisCat处理程序中不是.click()。此外,您不能从事件处理程序return。使用.next(".clickNos").find(".clicks")一起选择相对于点击的.clicks元素的下一个<img>元素;将匹配元素的.html()设置为.clicks实例的Cat属性。

  Cat.prototype.clickInc = function() {
    var _cat = this;
    $('#' + this.id).click(function() {
      _cat.clicks++;
      $(this).next(".clickNos").find(".clicks").html(" " +_cat.clicks);
    });
  }; 

jsfiddle https://jsfiddle.net/9cykvbyv/1/