knockout.js - 使用 knockout 的 jquery 模板内的单选按钮列表

标签 knockout.js jquery-templates

我正在使用带有 jquery 模板的 knockout ,我被困在模板中的某个位置。让我先向您展示代码。 这是我的模板

 <script type="text/x-jquery-tmpl" id="questionTemplate">
        <div class="questions">
               <div data-bind="text: QuestionText" style="font-weight:bold;"></div>
               {{if QuestionType == "FreeForm" }}
                       <textarea rows="3" cols="50" data-bind="value: ResponseValue"></textarea>
                   {{/if}}

                   {{if QuestionType != "FreeForm" }}
                       <table>
                        {{each(i,option) Options}}
                        <tr>
                       <td>
                       <input type="radio" data-bind="attr:{name:QuestionId},click:function(){ResponseValue=option.Value;}" />${option.Value}</td><td>- ${option.ResponsePercent} %</td> 
                       </tr>
                        {{/each}}
                       </table>    
                   {{/if}} 
            </div>
    </script>

这是我如何使用它

<div data-bind="template:{name:'questionTemplate',foreach:questionResponses()}">

所以基本上它所做的是,它循环每个问题响应并检查问题类型是否为 FreeForm 然后创建一个文本区域,否则它选择 QuestionResponse 的对象数组属性“Options”并使用 jquery {{each}} 来显示每个选项作为单选按钮。 在提交时,我选择“ResponseValue”属性的值,如果它是 textarea,那么我将获得 textarea 值,否则我将获得所选单选按钮的值。 这一切都工作得很好。

这就是它在 UI 中的样子

1. Tell me about yourself
[A Text Area Since it is a FreeForm Question]

2. How much you will rate yourself in MVC3?
RadioButton1
RadioButton2
RadioButton3

3. Blah Blah Blah?
RadioButton1
RadioButton2
RadioButton3
RadioButton4
RadioButton5
RadioButton6


... so.. on.. 

目前,我将“QuestionId”指定为单选按钮的名称,目的是使它们在问题中互斥。 所以第二个问题是所有 3 个单选按钮都会显示 name="111-1111-1111"。 第三个问题是所有 6 个单选按钮都会显示 name="222-2222-2222" 注意 - QuestionId 的类型为 Guid

唯一困扰我的小问题是,它不允许我更改我的选择,我的意思是说,如果我为问题 2 选择 RadioButton1,那么它不允许我选择 RadioButton2 或 3,每个问题也是如此。这种情况发生在火狐浏览器中。而 IE 9 甚至不允许选择页面中的任何单选按钮。

任何帮助将不胜感激

提前致谢

最佳答案

最好的选择是使用单选按钮的 checked 绑定(bind)。您的绑定(bind)将类似于:

<input type="radio" data-bind="attr:{name:QuestionId, value: option.Value }, checked: $data.ResponseValue" />${option.Value}</td>
  • name 属性确保它们是互斥的 在一个问题内。
  • value 属性决定了 checked 绑定(bind)将用于其值
  • checked 绑定(bind)将 将 option.Value 设置为选项的值

这是一个示例:http://jsfiddle.net/rniemeyer/ncERd/

关于knockout.js - 使用 knockout 的 jquery 模板内的单选按钮列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8135052/

相关文章:

javascript - 在 Bindinghandler 中添加/删除元素绑定(bind) - knockout

javascript - KnockoutJS 可见绑定(bind)不起作用

knockout.js - 使用 knockut 3 和 es5 插件的两种方式自定义绑定(bind)

jquery - JavaScript "Expected ' ]'"

jquery - 将 jQuery dataTables 与使用 tmpl 的 ajax 回调生成的表结合使用

validation - BreezeJS 不会自动解析使用 KnockoutJS 绑定(bind)保存为字符串的数字

javascript - knockout foreach 不匹配长度

knockout.js - 模板内的 knockout 绑定(bind)不起作用

jquery - 使用 Knockout JS 和 Jquery 模板的递归 tr

jQuery模板疑问: