KnockoutJS代码块中的动态ID

Cos*_*ore 6 asp.net sharepoint knockout.js

我已经对这个问题进行了一些研究,但我找不到任何真正有用的东西.

我的问题:

我有一个项目列表(在SharePoint中),我使用KnockoutJS foreach语句显示包含所有这些项目的表.像这样:

数量| 价格| Total_Price | RadioButton1 | RadioButton2

你可以看到有2个单选按钮,必须为它们使用id属性(因为我也使用JqueryUI - label for ='id of element' - )

我试过这样的事情>

代码示例:

.....

<%int i = 1; %>
<! - - ko foreach:Items - > ........

     <input type="radio" id="Yes+<%=i %>"/>
     <label for="Yes+<%=i %>" >Yes</label>
     <input type="radio" id="No+<%=i %>" />
     <label for="No+<%=i %>">No</label>

     </td>
Run Code Online (Sandbox Code Playgroud)

<%I ++; %>

<! - /ko - >

事情是asp代码不能识别ko foreach迭代.

有任何想法吗 ?谢谢

Mik*_*ons 8

你可以在Item视图模型上放置Id然后使用它吗?

< ! - - ko foreach: Items --> ........

 <input type="radio" data-bind="attr: { id: 'Yes' + Id }" />
 <label data-bind="attr: { 'for': 'Yes' + Id }" >Yes</label>
 <input type="radio" data-bind="attr: { id: 'No' + Id } />
 <label data-bind="attr: { 'for': 'No' + Id }">No</label>

 </td>
< !-- /ko -->
Run Code Online (Sandbox Code Playgroud)

或使用Macropus建议的可观察索引:

< ! - - ko foreach: Items --> ........

 <input type="radio" data-bind="attr: { id: 'Yes' + $index() }" />
 <label data-bind="attr: { 'for': 'Yes' + $index() }" >Yes</label>
 <input type="radio" data-bind="attr: { id: 'No' + $index() } />
 <label data-bind="attr: { 'for': 'No' + $index() }">No</label>

 </td>
< !-- /ko -->
Run Code Online (Sandbox Code Playgroud)

  • 我相信您需要使用 $index() 而不是 $index,因为它是可观察的。 (2认同)