最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to only show only the first element in foreach loop binding? - Stack Overflow

programmeradmin3浏览0评论

I am using knockout-2.2.0.js. I have created a foreach loop binding on observableArray and i want to show only first element in the array. For this i tried : (both not work)

First

        <!-- ko foreach: myArray -->
          <span data-bind="text: $data, visible: $index == 0"></span>
        <!-- /ko -->

Second

        <span data-bind="text: myArray[0]"></span>       

I know that there is a _destroy property which if set on any array element than that element will be excluded from the foreach loop binding in UI. But i dont want to use this in my case. Can anybody please tell me what i am doing wrong here ?

I am using knockout-2.2.0.js. I have created a foreach loop binding on observableArray and i want to show only first element in the array. For this i tried : (both not work)

First

        <!-- ko foreach: myArray -->
          <span data-bind="text: $data, visible: $index == 0"></span>
        <!-- /ko -->

Second

        <span data-bind="text: myArray[0]"></span>       

I know that there is a _destroy property which if set on any array element than that element will be excluded from the foreach loop binding in UI. But i dont want to use this in my case. Can anybody please tell me what i am doing wrong here ?

Share Improve this question edited Mar 3, 2013 at 12:11 Chris 10.4k1 gold badge40 silver badges46 bronze badges asked Mar 2, 2013 at 8:01 user1740381user1740381 2,1999 gold badges40 silver badges62 bronze badges 2
  • Can you avoid doing the foreach, and just do something like <span data-bind="text: myArray()[0], visible: true"></span> – Kal_Torak Commented Mar 2, 2013 at 8:15
  • If myArray is an observable, don't forget you have to call it like a function to access the indices. Also, have you run it in Chrome and checked the console (f12)? What error is it giving you? – Kal_Torak Commented Mar 2, 2013 at 8:19
Add a ment  | 

1 Answer 1

Reset to default 15

You are on the right track. But you have forgot to put out the () in both of your examples.

myArray an observable array and $index is an observable so they are functions so you need to call them as functions with () to get their values inside expressions.

So the correct bindings are:

<!-- ko foreach: myArray -->
    <span data-bind="text: $data, visible: $index() == 0"></span>
<!-- /ko -->

And

<span data-bind="text: myArray()[0]"></span>  

Demo JSFiddle.

Note: if you really just want to display the first item then you should prefer the text: myArray()[0] version because it is much cleaner there what you are trying to do.

发布评论

评论列表(0)

  1. 暂无评论