我有一个动态创建的列表视图,其中显示了位置列表以及这些位置的距离。对于其中一个位置(WFH),我不希望行<span data-bind="text: distanceBetweenPoints"></span><span> mi.</span>
出现。那么如何改变这一点,以便如果locationName =='WFH',则下一个span
不会显示任何内容。
这是HTML:
<div data-role="content">
<ul id="nearbyLocationsListView" data-bind="template: {name: 'locationsListTemplate', foreach: nearbyLocations}" data-role="listview" data-filter="false"></ul>
<script id="locationsListTemplate" type="text/html">
<li>
<div>
<span data-bind="text: locationName"></span>
<span data-bind="text: distanceBetweenPoints"></span><span> mi.</span>
</div>
</li>
</script>
</div>
以下是创建列表的位置:
function GetClosestLocationByCoordinates() {
var url = 'http://localhost/GetClosestLocationByCoordinates;
var jqxhr =
$.getJSON(url,
function (data) {
$.each(data.GetClosestLocationByCoordinatesResult, function (key, val) {
var distanceBetweenPoints = distance();
nearbyLocationsModel.addNearByLocations(val.LocationId, val.LocationName, val.NumberCheckedIn, distanceBetweenPoints);
});
ko.applyBindings(nearbyLocationsModel, document.getElementById("nearbyLocationsListView"));
})
}
答案 0 :(得分:1)
这应该有效:
<div data-role="content">
<ul id="nearbyLocationsListView" data-bind="template: {name: 'locationsListTemplate', foreach: nearbyLocations}" data-role="listview" data-filter="false"></ul>
<script id="locationsListTemplate" type="text/html">
<li>
<div>
<span data-bind="text: locationName"></span>
<div data-bind="visible: locationName() !== 'WFH'">
<span data-bind="text: distanceBetweenPoints"></span><span> mi.</span>
</div>
</div>
</li>
</script>
</div>
您还可以使用If
绑定代替visible
。
请注意,If
会从页面中删除元素,而visible
只是隐藏它。
可以在KO网站上找到更多详细信息:If binding,Visible binding
答案 1 :(得分:0)
要在不更改DOM结构的情况下这样做:
<div data-role="content">
<ul id="nearbyLocationsListView" data-bind="template: {name: 'locationsListTemplate', foreach: nearbyLocations}" data-role="listview" data-filter="false"></ul>
<script id="locationsListTemplate" type="text/html">
<li>
<div>
<span data-bind="text: locationName"></span>
<!-- ko if: locationName !== 'WFH' -->
<span data-bind="text: distanceBetweenPoints"></span><span> mi.</span>
<!-- /ko -->
</div>
</li>
</script>
</div>