简单值绑定到选择标记

时间:2014-12-09 08:00:05

标签: javascript select knockout.js binding

原谅我的无聊,我不会要求你为我创建一个软件解决方案,但我只想快速上课(或修复我的代码)如何让我的knockout.js工作。你知道,我是一个关于JS的全新手,我试图在这里找到一些东西:

<p>Show the number here: <span data-bind="text: showVal()" id="curr-value"></span>

                <select data-bind="selectedOptions:selectedBlah, options: $root.numberSet, value: currVal, optionsText: 'numName'">
                </select>

            </p>

            <script type="text/javascript">

              function NumbersSViewModel() {
                self.numberSet = [
                  { numName: "Two in Decimal is", currVal: 2 },
                  { numName: "Three in Decimal is", currVal: 3 },
                  { numName: "Four in Decimal is", currVal: 4 },
                ]

                self.selectedBlah = ko.observableArray([]);

                self.showVal = ko.computed(function() {
                    var value = currVal().toString();
                    return value;
                });

              }

              ko.applyBindings(new NumberSViewModel()); </script>

所以,我想要做的是,如果在值上设置下拉菜单,则跨度上的文本值会发生变化。我确定它是可能的,我无法让它发挥作用。

1 个答案:

答案 0 :(得分:0)

使用Javascript:

function NumbersViewModel() {
    var self = this;

    self.numberSet = [
        { numName: "Two in Decimal is", curVal: 2 },
        { numName: "Three in Decimal is", curVal: 3 },
        { numName: "Four in Decimal is", curVal: 4 },
    ];

    self.selectedNumber = ko.observable();
    }

ko.applyBindings(new NumbersViewModel()); 

HTML:

<select data-bind="options: numberSet,
                   optionsText: 'numName',
                   optionsValue: 'curVal',
                   value: selectedNumber"></select>

Show the number here:
<span data-bind="text: selectedNumber" id="curr-value"></span>

请参阅Fiddle