I want to show only 2 names at a time from a list

2020-05-07 06:16发布

I want to show only first 2 things which are present in an array instead of all and then b y clicking on button next 2 names comes up till the last, but the code which I am trying is not working. I am giving the code please tell the bug. Can you help me in correcting the code of knoctout js .

In Javascript

EventBE.displayCount = ko.observable(2);
EventBE.readMore = function() { EventBE.displayCount(EventBE.displayCount() + 2); };

in html

div class="slide">
    <button type="button" data-bind"click: EventBE.readMore,visible: 
        EventBE.displayCount() < EventBE.WhoElseAttends.length">Read More</button>
        <ul  data-bind="foreach:EventBE.WhoElseAttends.slice(0, 
             EventBE.displayCount())">
            <li >
                <span data-bind="text:FirstName"></span>
                <span data-bind="text:LastName"></span>,
                <span data-bind="text:Company"></span>
             </li>
        </ul>                  
   <span data-bind="if:EventBE.WhoElseAttends.length <0">No Attendees</span>                    
</div>

1条回答
何必那么认真
2楼-- · 2020-05-07 07:19

Here's the working HTML:

<div class="slide">
    <button type="button" data-bind="click: readMore, visible: displayCount() < WhoElseAttends().length">Read More</button>
    <ul data-bind="foreach: WhoElseAttends.slice(0, displayCount())">
        <li>
            <span data-bind="text:FirstName"></span>
            <span data-bind="text:LastName"></span>,
            <span data-bind="text:Company"></span>
        </li>
    </ul>                  
    <span data-bind="if: WhoElseAttends.length <0">No Attendees</span>                    
</div>

And the accompanying Knockout view model:

function viewModel() {
    this.displayCount = ko.observable(2);

    this.readMore = function() {
        this.displayCount(this.displayCount() + 2);
    };

    this.WhoElseAttends = ko.observableArray([]);

    for (var i = 0; i < 10; i++) {
        this.WhoElseAttends.push({FirstName : "John", LastName : "Smith", Company : "None"});
    }
}

ko.applyBindings(new viewModel());

I've also rendered this code in the following jfiddle: http://jsfiddle.net/Bg5CF/17/

查看更多
登录 后发表回答