简体   繁体   English

带Knockout.js的单选按钮列表

[英]Radio Button List with Knockout.js

I'm trying to build a list of radio buttons with labels so that you can click the label to check the radio item. 我正在尝试使用标签构建一个单选按钮列表,以便您可以单击标签来检查单选项。 What I have works fine in Chrome, but not IE7. 我在Chrome中运行得很好,但不是IE7。 The HTML that get's spit out seems like it is correct, but when I click on the label, the corresponding radio button doesn't get selected. 得到吐出的HTML似乎是正确的,但当我点击标签时,相应的单选按钮不会被选中。

JavaScript JavaScript的

function ReuqestType(id, name, billable) {
    this.id = id;
    this.name = name;
    this.billable = billable;
}

function RequestViewModel() {
    var self = this;

    self.availableRequestTypes = [
        new ReuqestType(1, "Travel", true),
        new ReuqestType(2, "Bill Only", false),
        new ReuqestType(3, "Both", true)
    ];

    self.selectedRequestType = ko.observable();
}

HTML HTML

Request Type
<br />
<!-- ko foreach: availableRequestTypes -->
<input type="radio" name="requestType" data-bind="value:id, attr: {'id': 'rt'+ id}" />
<label data-bind="text: name, attr:{'for':'rt'+id}">
</label>
<!-- /ko -->

What is the preferred way to do this? 这样做的首选方法是什么?

从最新版本的Knockout(2.1.0)开始,这似乎正常工作。

I'm unfamiliar with knockout.js, but you can normally bind label's to inputs just by making the label wrap around the input box too. 我不熟悉knockout.js,但你通常可以通过使标签环绕输入框来将标签绑定到输入。

http://jsfiddle.net/QD2qC/ http://jsfiddle.net/QD2qC/

It looks like your HTML is fine. 看起来你的HTML很好。 It could be a quirk of IE7 not being able to acknowledge clicks of labels that have been generated dynamically. IE7的一个怪癖可能是无法确认动态生成的标签点击。

If you can't find a proper answer, you could always use this workaround : 如果找不到合适的答案,可以随时使用此解决方法

$('label').on('click', function() {
   var labelId = $(this).attr('for');
   $('#' + labelId ).trigger('click');
});

I have changed it slightly by using on() instead of click() to account for these labels being generated dynamically. 我通过使用on()而不是click()来稍微改变它,以便考虑动态生成这些标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM