javascript Knockoutjs“无法解析绑定”错误,但代码有效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10129441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
knockoutjs "Unable to parse bindings" error, but code works
提问by Jason More
I've been using knockout for a while, but in writing up some code examples this one has me stumped. The code works exactly as I'm expecting, where the click button toggles the visible, but I'm still getting an error:
我已经使用淘汰赛一段时间了,但是在编写一些代码示例时,这个代码示例让我感到困惑。代码完全按照我的预期工作,点击按钮切换可见,但我仍然收到错误:
JsFiddle: http://jsfiddle.net/JasonMore/hCdF8/1/
JsFiddle:http: //jsfiddle.net/JasonMore/hCdF8/1/
Uncaught Error: Unable to parse bindings.
Message: ReferenceError: answerClick is not defined;
Bindings value: click: answerClick
from
从
<ul data-bind="foreach: answers">
<li>
<a class="hiddenButton" href="#" data-bind="click: answerClick" />
<div class="answerNumber" data-bind="visible: showAnswerNumber">
<h2 data-bind="text: answerNumber" />
</div>
<div class="answer" data-bind="visible: showAnswerText">
<p data-bind="text:text" />
<p data-bind="text: points" />
</div>
</li>
</ul>
<script type="text/javascript">
var answerViewModel = function () {
var self = this;
//clicks
self.answerClick = function () {
self.showAnswerNumber(!self.showAnswerNumber());
};
//observables
self.answerNumber = ko.observable();
self.text = ko.observable();
self.points = ko.observable();
self.showAnswerNumber = ko.observable(true);
//computed
self.showAnswerText = ko.computed(function () {
return !self.showAnswerNumber();
});
};
var roundViewModel = function () {
var self = this;
self.answers = ko.observableArray();
};
var answer1 = new answerViewModel();
answer1.text = "foo answer";
answer1.answerNumber = 1;
answer1.points = 50;
var vm = new roundViewModel();
vm.answers.push(answer1);
ko.applyBindings(vm);
</script>
回答by RP Niemeyer
Because you are closing your anchor tag: <a />
, it is getting rendered in a strange way where an extra anchor tag is outside of the foreach
and not in a context where answerClick
is a valid function.
因为您正在关闭锚标记: <a />
,所以它以一种奇怪的方式呈现,其中额外的锚标记在 之外foreach
而不是在answerClick
有效函数的上下文中。
I am not sure what content that you want to use for your link, but you need to have an opening and closing tag like:
我不确定您要为链接使用什么内容,但您需要有一个开始和结束标记,例如:
<a class="hiddenButton" href="#" data-bind="click: answerClick">link</a>
<a class="hiddenButton" href="#" data-bind="click: answerClick">link</a>
Not sure if you intended to wrap the content in that link, but that is where your issue lies.
不确定您是否打算将内容包装在该链接中,但这就是您的问题所在。