我有一个包含特定值的下拉列表。我在列表中有三个值。如果我选择第三个选项,我需要显示一个div,它有两个文本字段,否则隐藏它们。
这是我的代码: -
HTML:
<div class="control-group">
<div class="row">
<div class="col-md-3">
<label class="placeholder">{package}.property</label>
@Html.DropDownList("mProperty", new SelectList(Enum.GetNames(typeof({package}.property))), new { @class = "form-control", type = "text", id = "mProperty" })
</div>
<div id="weights" >
<span class="col-md-6" id="lblNumerator" >{package}.property2@Html.DropDownList("field1", new SelectList(numerators), new { @class = "form-control numerator-dropdown", type = "text", id = "field1" })</span><br />
<span class="col-md-6" id="lblDenominator">{package}.property3 @Html.DropDownList("field2", new SelectList(denominators), new { @class = "form-control", type = "text", id = "field2" })</span>
</div>
<br />
<br />
<div class="row">
<div class="col-md-12">
<label class="placeholder">Account</label>
@Html.DropDownList("field0", new SelectList(accounts), new { @class = "form-control allaccounts-dropdown", type = "text", id = "field0" })
</div>
</div>
</div>
我想展示div&#34; weight&#34;与字段&#34; lblNumerator&#34;和&#34; lblNumerator&#34;如果我从下拉列表中选择第3个值&#34; mProperty&#34;。
我是Knockout的新手,非常感谢任何帮助。感谢
答案 0 :(得分:3)
此代码与您的Razor-html足够接近,我认为这个想法很明确。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select data-bind="selectedOptions: options">
<option value="option 1" selected>Option 1</option>
<option value="option 2">Option 2</option>
<option value="option 3">Option 3</option>
</select>
<div data-bind="visible: shouldShowText">
<h2>some hidden text</h2>
</div>
<hr />
<div data-bind="text: ko.toJSON(viewModel)"></div>
<script src="knockout.js"></script>
<script>
function ViewModel() {
var availableOptions = document.querySelectorAll('option');
availableOptions = Array.prototype.map.call(availableOptions, function(o) { return o.value; })
var firstOption = availableOptions[0];
this.options = ko.observableArray([firstOption]);
this.shouldShowText = ko.computed(function() {
var selectedOption = this.options()[0];
return availableOptions.indexOf(selectedOption) === 2;
}, this);
}
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
</script>
</body>
</html>
工作插件是here