Динамически показать / скрыть с Knockout JS

Я пытаюсь сделать что-то простое с KnockoutJS - динамически показывать раздел, когда радиогруппа имеет значение 'y' .

 'use strict'; console.log('running js..', ko); var ViewModel = function() { this.termsAccepted = ko.observable('n'); }; // Bind our ViewModel to our View ko.applyBindings(new ViewModel()); 
 <script>console.log('loading knockout')</script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <script>console.log('knockout loaded')</script> <h4>Dynamically hide / show section</h4> <p>I would like to show a section when the terms are actually accepted, and hide it otherwise</p> <p><strong>Terms accepted</strong> <span style="color: red" data-bind="text: termsAccepted"/></p> <p><input type="radio" name="esign" value="y" data-bind="checked: termsAccepted"> <label for="esignTrue">I agree.</label> <input type="radio" name="esign" value="n" data-bind="checked: termsAccepted"> <label for="esignFalse">I do not agree.</label></p> <div data-bind="visible: termsAccepted"> Only showing when terms are accepted... </div> <div data-bind="visible: termsAccepted === 'y'"> Only showing when terms are accepted... </div> <!-- ko if: termsAccepted === 'y' --> <div> Only showing when terms are accepted... </div> <!-- /ko --> 

Всего 1 ответ


Поскольку вы привязываетесь к выражению функции, а не просто к наблюдаемой, вы должны развернуть наблюдаемые в выражении паренами.

https://knockoutjs.com/documentation/binding-syntax.html

 'use strict'; var ViewModel = function() { this.termsAccepted = ko.observable('n'); }; // Bind our ViewModel to our View ko.applyBindings(new ViewModel()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <h4>Dynamically hide / show section</h4> <p>I would like to show a section when the terms are actually accepted, and hide it otherwise</p> <p><strong>Terms accepted</strong> <span style="color: red" data-bind="text: termsAccepted"/></p> <p><input type="radio" name="esign" value="y" data-bind="checked: termsAccepted"> <label for="esignTrue">I agree.</label> <input type="radio" name="esign" value="n" data-bind="checked: termsAccepted"> <label for="esignFalse">I do not agree.</label></p> <div data-bind="visible: termsAccepted() === 'y'"> Only showing when terms are accepted... </div> <!-- ko if: termsAccepted() === 'y' --> <div> Only showing when terms are accepted... </div> <!-- /ko --> 


Есть идеи?

10000