gpt4 book ai didi

javascript - 单击图像会在 knockoutJS 中提供递增的值

转载 作者:行者123 更新时间:2023-11-28 17:42:10 25 4
gpt4 key购买 nike

以下是html和JS代码

HTML 正文。

    <h2 data-bind="text: currentCat().name" id="cat-name"></h2>
<div data-bind="text: currentCat().clickCount" id="cat-count"></div>
<img src="" data-bind="click: incrementCount(), attr: {src: currentCat().imgSrc}" id="cat-img" alt="cute cat">
<h4>NickNames</h4>
<ul data-bind="foreach: currentCat().nickNames">
<li data-bind="text: name"></li>
</ul>
</div>
<script src="js/lib/knockout-3.2.0.js"></script>
<script src="js/app.js"></script>

JS代码

 var ViewModel = function() {
this.currentCat = ko.observable( new Cat() );
console.log(this.currentCat().clickCount())
this.incrementCount = function(){


this.currentCat().clickCount(this.currentCat().clickCount() + 1);
};
}

var Cat = function() {
this.clickCount = ko.observable(0);
this.name = ko.observable('Tabby');
this.imgSrc = ko.observable('tabby.jpg');
this.imgAttribution = ko.observable('XXXX');

this.nickNames = ko.observableArray(
[
{name: 'Tabtab'},
{name: 'T-bone'},
{name: 'Mr. T'},
{name: 'Tabitha Tab Tabby'}
]
);
}
ko.applyBindings(new ViewModel())

但是,在渲染 HTML 页面时,点击计数为 1,而不是预期值 0。我错过了什么吗?

最佳答案

click binding需要一个函数引用,而不是一个要运行的表达式。当绑定(bind)初始化时,您提供的表达式将立即运行。您需要更改绑定(bind)以提供函数本身:

data-bind="click: incrementCount"

关于javascript - 单击图像会在 knockoutJS 中提供递增的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47682771/

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