我正在尝试使用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 -->
这似乎很简单,但是这些部分并未按预期隐藏/显示。
我已经证实这不是因为使用了here所述的自动关闭标签。
答案 0 :(得分:2)
因为要绑定到函数表达式而不是简单地绑定到可观察对象,所以必须用括号将表达式中的可观察对象展开。
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 -->