0

This code displays two cats and the number of times each cat is clicked, how can I increment the .clicks property of each cat from inside the Cat.prototype.clickInc() method?

    $(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();
}


});
Reme
  • 11
  • 2
  • The irregular indentation in the code here makes this question ***very*** difficult to read. Just a tip: you will get help faster if you present your problem in an easy-to-read format with properly indented code (and anyone who works on your code in the future will thank you, too!) – apsillers Apr 19 '17 at 18:23
  • @FelixKling `javascript` at Question has more issues that only accessing correct `this` within event handler, including attempt to `return` from within `click` handler instead of setting `.innerHTML` of appropriate element, which is not addressed at linked Question/Answers – guest271314 Apr 19 '17 at 18:34
  • 1
    @guest271314 I agree and reopened. Like Felix, I didn't understand the OP wanted the `` element to be updated, but now that you point it out, that seems like the correct interpretation of the question. – apsillers Apr 19 '17 at 19:02

1 Answers1

1

this is not Cat within .click() handler. Also, you cannot return from an event handler. Use .next(".clickNos") with .find(".clicks") to select next .clicks element relative to clicked <img> element; set .html() of matched element to .clicks property of Cat instance.

  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/

guest271314
  • 1
  • 15
  • 104
  • 177