我有一个淘汰视图模型功能,单击按钮时不会调用。 可能我错过了什么。我正在运行VS2010 IDE中的代码。我在jsfiddle中测试相同的代码 它正在那里工作,但当我尝试从VS2010 IDE运行相同的代码,然后它无法正常工作。任何帮助 不胜感激。感谢
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
#dash
{
max-height: 128px;
overflow: hidden;
}
#dash div
{
border: 1px solid #de2345;
padding: 4px;
margin: 2px;
line-height: 20px;
box-sizing: border-box;
}
#dash div:before
{
content: '--> ';
}
</style>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"/>
<script type="text/javascript">
function TableModel()
{
var self = this;
self.Counter = 1;
self.rows = ko.observableArray([]),
self.addRow = function () {
alert('pp');
self.rows.push(self.Counter + ' ' + new Date());
self.Counter++;
setTimeout(function () {
self.rows.shift();
self.Counter--;
}, 3000 + self.rows().length * 1000);
return false;
}
}
ko.applyBindings(new TableModel());
</script>
</head>
<body>
<form id="form1" runat="server">
<button id="button" data-bind="click: addRow" type="button">click</button>
<div id="dash" data-bind="foreach: rows">
<div data-bind="text:$data">
</div>
</div>
</form>
</body>
</html>
答案 0 :(得分:1)
加载DOM时必须调用ko.applyBindings
。另见documentation。
您可以通过以下方式实现此目的:
body
head
部分中,然后将``ko.applyBindings`的调用包装在一个支持DOM的处理程序中,例如jQuery’s ready function 如果您不使用jQuery,只需将脚本移到底部:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script>
</head>
<body>
<form id="form1" runat="server">
<button id="button" data-bind="click: addRow" type="button">click</button>
<div id="dash" data-bind="foreach: rows">
<div data-bind="text:$data">
</div>
</div>
</form>
<script type="text/javascript">
function TableModel()
{
var self = this;
self.Counter = 1;
self.rows = ko.observableArray([]),
self.addRow = function () {
alert('pp');
self.rows.push(self.Counter + ' ' + new Date());
self.Counter++;
setTimeout(function () {
self.rows.shift();
self.Counter--;
}, 3000 + self.rows().length * 1000);
return false;
}
}
ko.applyBindings(new TableModel());
</script>
</body>
</html>