0

I create a list of items by means of the foreach binding using Knockout.js. When all the items of the foreach bindings are rendered, I would like to search for an item of a specific class called "focused" and scroll a window to that item.

That will happen only once on page load as I do not add or remove the items.

How can I do it?

4

1 回答 1

1

You can use property afterRender of foreach binding.

<div data-bind="foreach: { data: items, afterRender: doSomething }">
    <div data-bind="text: $data">
</div>

Your viewModel:

var vm = {
   doSomethingInvoked: false,
   items: ko.observableArray(['apple', 'banan']),
   doSomething: function (elements) {
       if (!doSomethingInvoked) { // prevent invoking multiple times
           var offsetTop = $(elements).filter('.focus').offset().top;
           $('html,body').scrollTop(offsetTop);
           doSomethingInvoked = true;
       }
   }
};
于 2013-02-17T09:25:23.227 回答