我是Knockout的新手,並且正在創建原型。我正在嘗試使用div上的可見綁定來僅在單擊「菜單選項」時顯示。但是,當我創建條件時,它似乎不起作用。敲除js可見綁定似乎沒有工作
這裏是我的源:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript" src="Scripts/knockout.js"></script>
<script type="text/javascript" src="Scripts/Models.js"></script>
<script type="text/javascript">
$(function() {
function BillingInformation() {
this.accountNumber = ko.observable('4111111111111111');
this.cardType = ko.observable('Visa');
this.expirationDate = ko.observable('2016-01-15');
}
function Invoice(billingDate, amount, paid) {
this.billingDate = billingDate;
this.amount = amount;
this.paid = paid;
}
function Pet(name, breed, age) {
this.name = name;
this.breed = breed;
this.age = age;
}
function PrototypeViewModel() {
this.menu = [{ folderName: 'Customer Information', folderId: 0 },
{ folderName: 'Customer Information Edit', folderId: 1 },
{ folderName: 'Billing Information Edit', folderId: 2 },
{ folderName: 'Pets', folderId: 3 },
{ folderName: 'Invoices', folderId: 4 }];
this.customer = { firstName: 'Wesley', lastName: 'Snipes', email: '[email protected]' };
this.billingInformation = new BillingInformation();
this.pets = ko.observableArray(
[
new Pet('Poopy', 'Great Dane', 3),
new Pet('Pokey', 'Great Dane', 2)
]);
this.invoices = ko.observableArray(
[
new Invoice('2012-11-15', 24.35, true),
new Invoice('2012-12-15', 24.35, true),
new Invoice('2013-01-15', 34.43, false)
]);
this.selectedMenuOptionId = ko.observable();
this.selectMenuOption = function (menuOption) {
this.selectedMenuOptionId = menuOption.folderId;
};
this.isMenuSelected = function(menuSelected) {
return this.selectedMenuOptionId == menuSelected;
};
}
ko.applyBindings(new PrototypeViewModel());
});
</script>
</head>
<body>
<ul data-bind="foreach: menu">
<li data-bind="text: $data.folderName, click: $root.selectMenuOption"></li>
</ul>
<div data-bind="visible: isMenuSelected(0)">
<p>selected customer menu</p>
</div>
</body>
</html>
我試圖簡單地設置可視條件做一個字符串比較,但似乎並沒有工作。正如您現在所看到的,我正在使用isMenuSelected函數嘗試使其工作,但也失敗了。我也沒有得到任何腳本錯誤。請問我在這裏錯過了什麼?
這工作!所以謝謝。有趣的是,它最初並不起作用。我必須創建一個名爲self的變量(從knockout教程中獲得了這個想法)並將其設置爲'this'。之後,它完全運作! – 2013-02-18 17:55:04
是的,「自我」和「這個」之間的區別起初似乎有點神祕。很高興我能幫上忙! – bdesham 2013-02-18 17:57:59