سؤال

I have an observableArray in my Knockout app and I'm wondering how I can go about selecting only the targeted object within the array.

I have the following code which calculates the total of all 'value's within the array but I'd like to be able to just select, say, only the second 'value' within the array.

self.csu_treatment_inputs = ko.observableArray([
                {
                    value: ko.observable(10),
                    image: ko.observable('')
                },
                {
                    value: ko.observable(120),
                    image: ko.observable('')
                },
                {
                    value: ko.observable(160),
                    image: ko.observable('')
                },

            ]);

self.totaltest = ko.computed(function () {
            var total = 0;
            ko.utils.arrayFilter(self.value_inputs(), function (item) {
                  total += parseFloat(ko.utils.unwrapObservable(item.value));
            });
            return total;
    });
هل كانت مفيدة؟

المحلول

To bind to the second value, use this code:

<span data-bind='text: csu_treatment_inputs()[1].value'></span>

Exemple: http://jsfiddle.net/v6T5T/

If you want to access an element from javascript, use this:

total+= parseFloat(self.test_values()[i].value());

Exemple: http://jsfiddle.net/v6T5T/2/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top