2013-10-06 55 views
0

雖然我想出瞭如何獲取數組中的所有元素,但我試圖獲取屬於第一個元素的元素。我正在使用Backbone.js並試圖編輯我的一個模板。我得到的曲目信息來自JSON文件。我可以在我的HTML文件中執行此操作,還是必須編輯我的.js文件?Backbone.js從JSON文件中獲取第一個元素

HTML:

<script type="text/template" id="lesson-template"> 
     <span class="lesson-title"><%= title %></span> 
     <select class="sel"> 
      <% _.each(tracks, function(track) { %> //this lets me loop through each of them 
       <option value = "<%= track.text %>" ><%= track.title %></option> 
      <% }); %>   
      </select> 
//Now I want to figure out a way to just get the track.text of the first track here and put it in tracktext! 
      <p id="tracktext">Hello World!</p> 
     </script> 

回答

1
<p id="tracktext"><%= tracks[0].text %></p> 

你似乎沒有使用骨幹的集合或模型在這裏。這只是一個關於JavaScript和下劃線模板的問題嗎?

+0

是的,那是在我的JS文件。但是,是的問題是關於JavaScript的;我是一名初學者。謝謝! – Robs

+0

然而,一個簡單的問題是,你能解釋<%_.each(音軌,函數(音軌){%>的工作原理)嗎? – Robs

+0

這裏是註釋的源代碼http://documentcloud.github.io/underscore/docs/underscore。 html#section-15總之,它使用基本的javascript for循環來按順序訪問數組中的每個元素,並且爲每個元素調用您提供的函數,將當前元素作爲參數傳遞給函數。 –

相關問題