仅当从列表中选择了一个特定选项时,才显示相关内容

Display related content only if one particular option is selected from the list

本文关键字:选项 显示 一个 列表 选择      更新时间:2023-09-26

现在,如果我选择列表中的任何选项,它将显示一个输入字段,但我想更改它的方式是仅在选择"其他"时才显示输入。

我该怎么做?

$(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>

使其成为计算可观察量,这将更具单元可测试和可重用性。

$(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());
});
<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>

只需检查绑定的可见性检查:

<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>
相关文章: