Javascript “奇怪”;“未定义”;错误
我的viewmodel中有以下代码:Javascript “奇怪”;“未定义”;错误,javascript,jquery,knockout.js,Javascript,Jquery,Knockout.js,我的viewmodel中有以下代码: CA = function (clientNum) { this.CAName = null; this.CAAdress = null; this.CAIdNum = null; this.CAContact = null; this.CANote = null; this.CAType = null; this.clNum = clientNum; }, viewModelNewCredit = f
CA = function (clientNum) {
this.CAName = null;
this.CAAdress = null;
this.CAIdNum = null;
this.CAContact = null;
this.CANote = null;
this.CAType = null;
this.clNum = clientNum;
},
viewModelNewCredit = function () {
var
creditRows = ko.observableArray(),
showView = ko.observable(),
sessionTicket = ko.observable(),
loggedUser = ko.observable()
newCreditRows = function () {
console.log(this.clientNum());
this.creditRows.push(new CA(this.clientNum()));
console.log(creditRows());
},
remove = function (ca) {
this.creditRows.remove(ca);
};
return {
creditRows: creditRows,
showView: showView,
sessionTicket: sessionTicket,
loggedUser: loggedUser,
viewModelNewCredit: viewModelNewCredit,
remove: remove
};
},
在我的HTML中,我有:
<tbody data-bind="foreach: creditRows">
<tr>
<td>
<select name="CAType" id="CAType" data-bind="value: CAType" style="width: 8em;">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</td>
<td>
<input type="text" name="CAName" id="CAName" data-bind="value: CAName" style="width: 15em;">
</td>
<td>
<input type="text" name="CAAdress" data-bind="value: CAAdress" style="width: 15em;">
</td>
<td>
<input type="text" name="CAIdNum" data-bind="value: CAIdNum" style="width: 6em;">
</td>
<td>
<input type="text" name="CAContact" data-bind="value: CAContact" style="width: 10em;">
</td>
<td>
<input type="text" name="CANote" data-bind="value: CANote" style="width: 15em;">
</td>
<td>
<img src="/projMonitoring/js/images/close.jpg" alt="Close" data-bind="click: remove.bind($parent)">
</td>
</tr>
</tbody>
</table>
<button type="button" id="newRow" class="button" data-bind="click: newCreditRows">Add new row</button>
<button type="button" id="OpenModal" class="button" data-bind="click: openModal">Open Modal</button>
1.
2.
3.
4.
添加新行
开放模态
这行代码:
应该执行一个函数,但我得到的是:
错误:无法分析绑定。消息:ReferenceError:未定义删除;绑定值:单击:删除.bind($parent)
你知道发生了什么事吗?我很确定我遗漏了一些非常小的东西,但我无法发现它。您需要一个视图模型的实例。按以下方式更改绑定:
var x = new viewModelNewCredit();
ko.applyBindings(x);
在.的演示中,您处于foreach的上下文中,因此当您调用remove方法时,您试图在所遍历的数组中的元素上调用它。相反,您需要在ViewModel上调用它:
<img src="/projMonitoring/js/images/close.jpg" alt="Close" data-bind="click: $root.remove">
正如上面所说remove
未定义…好的,但我现在得到的是:TypeError:this.creditRows未定义
:(记录this
并查看它所指的内容,我猜,这是窗口范围。尝试将this
封装到VM构造函数的开头:var self=this
,然后使用self
替代找到的解决方案!感谢您的帮助!