现在,如果我选择列表中的任何选项,它将显示一个输入字段,但我想改变它,只有在选择“其他”时才显示输入字段。
我该怎么做?
$(document).ready(function() {
var viewModel = function() {
var self = this;
self.actions_new_location = ["Studio", "Conservation Studio", "Gallery", "Other"];
self.actions_new_location_selected = ko.observable();
};
ko.applyBindings(new viewModel());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<li class="row">
<div class="col-3">
<label>Location of Photography</label>
</div>
<div class="col-3">
<select data-bind="options: actions_new_location, value: actions_new_location_selected, optionsCaption: 'Choose...'"></select>
</div>
</li>
<!-- to be shown only if "Other" is selected -->
<li class="row" data-bind="visible: actions_new_location_selected">
<div class="col-3 col-offset-3">
<label>Please describe
<input type="text" data-bind="" />
</label>
</div>
</li>
答案 0 :(得分:2)
使它成为一个计算的可观察量,这将更加可单元测试并可重复使用。
$(document).ready(function() {
var viewModel = function() {
var self = this;
self.actions_new_location = ["Studio", "Conservation Studio", "Gallery", "Other"];
self.actions_new_location_selected = ko.observable();
self.actions_other_selected = ko.computed(function() {
return self.actions_new_location_selected() === "Other";
});
};
ko.applyBindings(new viewModel());
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<li class="row">
<div class="col-3">
<label>Location of Photography</label>
</div>
<div class="col-3">
<select data-bind="options: actions_new_location, value: actions_new_location_selected, optionsCaption: 'Choose...'"></select>
</div>
</li>
<!-- to be shown only if "Other" is selected -->
<li class="row" data-bind="visible: actions_other_selected">
<div class="col-3 col-offset-3">
<label>Please describe
<input type="text" data-bind="" />
</label>
</div>
</li>
&#13;
答案 1 :(得分:1)
只需检查绑定的可见性检查:
<li class="row" data-bind="visible: actions_new_location_selected() === 'Other'">
<div class="col-3 col-offset-3">
<label>Please describe
<input type="text" data-bind="" />
</label>
</div>
</li>