在列表视图中隐藏特定的html

时间:2012-12-18 18:27:52

标签: jquery listview knockout.js

我有一个动态创建的列表视图,其中显示了位置列表以及这些位置的距离。对于其中一个位置(WFH),我不希望行<span data-bind="text: distanceBetweenPoints"></span><span>&nbsp; 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>&nbsp; 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"));
    })
}

2 个答案:

答案 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>&nbsp; mi.</span>
                </div>
            </div>
        </li>
    </script>
</div>

您还可以使用If绑定代替visible。 请注意,If会从页面中删除元素,而visible只是隐藏它。

可以在KO网站上找到更多详细信息:If bindingVisible 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>&nbsp; mi.</span>
                <!-- /ko -->
            </div>
        </li>
    </script>
</div>