从json对象获取复选框值

时间:2014-02-27 06:26:48

标签: javascript knockout.js frameworks

我目前正在学习并使用淘汰赛js框架。我有一套基本的联系人字段。我可以毫无问题地添加联系人。但是我在设置性别malefemale的值方面遇到了困难。我已正确声明但在阅读JSON对象时,它不会显示任何性别值。为什么联系人不是男性还是女性? JSFIDDLE

var initialData = [{
    firstName: "Jenny",
    lastName: "LaRusso",
    phone: "(555) 121-2121",
    alt_phone: "(555) 123-4567",
    male: false,
    female: true
}, {
    firstName: "Sensei",
    lastName: "Miyagi",
    phone: "(555) 444-2222",
    alt_phone: "(555) 999-1212",
    male: true,
    female: false
}];

var ContactsModel = function (contacts) {
    var self = this;
    self.contacts = ko.observableArray([]);

    ko.utils.arrayForEach(contacts, function (contact) {
        self.contacts.push({
            firstName: contact.firstName,
            lastName: contact.lastName,
            phone: contact.phone,
            alt_phone: contact.alt_phone,
            male: contact.male,
            female: contact.female
        });
    });

    self.addContact = function () {
        self.contacts.push({
            firstName: "",
            lastName: "",
            phone: "",
            alt_phone: "",
            male: false,
            female: false
        });
    };

    self.removeContact = function (contact) {
        self.contacts.remove(contact);
    };

    self.addPhone = function (contact) {
        contact.phones.push({
            number: ""
        });
    };

    self.removePhone = function (phone) {
        $.each(self.contacts(), function () {
            this.phones.remove(phone)
        })
    };

    self.save = function () {
        self.lastSavedJson(JSON.stringify(ko.toJS(self.contacts), null, 2));
    };

    self.lastSavedJson = ko.observable("")
};

ko.applyBindings(new ContactsModel(initialData));

1 个答案:

答案 0 :(得分:1)

要在knockout.js中启用复选框,正确的语法是

在HTML中声明复选框

<input type='checkbox' data-bind="checked: bindName" />

通过knockout.js启用/禁用复选框

<script type="text/javascript">
var viewModel = {
    bindName : ko.observable(false),
};
</script>

将javascript代码更改为

ko.utils.arrayForEach(contacts, function (contact) {
    self.contacts.push({
        firstName: contact.firstName,
        lastName: contact.lastName,
        phone: contact.phone,
        alt_phone: contact.alt_phone,
        male: ko.observable(contact.male), /* Line Modified */
        female: ko.observable(contact.female) /* Line Modified */
    });

在HTML中更改复选框的代码

 Male <input type="checkbox" data-bind='checked: male' />
 Female <input type="checkbox" data-bind='checked: female' />

JS小提琴链接 - http://jsfiddle.net/dLbY7/15/