gpt4 book ai didi

javascript - 从原型(prototype)函数内的函数增加 this.clicks

转载 作者:行者123 更新时间:2023-12-03 04:30:41 25 4
gpt4 key购买 nike

此代码显示两只猫以及每只猫被点击的次数,如何从 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();
}


});

最佳答案

this不是Cat .click()内处理程序。另外,你不能return来自事件处理程序。使用.next(".clickNos").find(".clicks")选择下一个.clicks相对于单击的元素 <img>元素;设置.html()匹配元素到 .clicks Cat的属性(property)实例。

  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/

关于javascript - 从原型(prototype)函数内的函数增加 this.clicks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43503275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com