javascript 淘汰赛中的标记复选框和单选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13660608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Labelling Checkbox and Radio in knockout
提问by Rups
In html, when we click on the text or hover over the text of a radio button or checkbox, we are able to select it with the html as shown below:
在 html 中,当我们单击文本或将鼠标悬停在单选按钮或复选框的文本上时,我们可以使用 html 选择它,如下所示:
<label>
<input type="checkbox" />option 1
</label>
OR
或者
<input id="checkboxid" type="checkbox" />
<label for="checkboxid">option 1</label>
I am trying to get the same behavior with knockout, but unable to find much help on the same:
我试图通过淘汰赛获得相同的行为,但无法找到太多帮助:
<label data-bind="text: $data.optiontext">
<input type="checkbox" data-bind="value: $data.optionvalue, checked: $parent.selectedOptions" />
</label>
The View (or html) is below (Note the below code does not contain the above html, so when you try it you will need to make the above changes and check it):
视图(或 html)在下面(注意下面的代码不包含上面的 html,所以当你尝试它时,你需要进行上面的更改并检查它):
<div data-bind="foreach: options">
<input type="checkbox" data-bind="value: $data.optionvalue, checked: $parent.selectedOptions" />
<label data-bind="text: $data.optiontext"></label>
</div>
<hr />
<div data-bind="text: selectedOptionsList"></div>?
Here is the view model:
这是视图模型:
var viewModel = {
options: [
{ optiontext: 'Simple', optionvalue: "1" },
{ optiontext: 'Advanced', optionvalue: "2" }
],
selectedOptions: ko.observableArray(["2"])
};
viewModel.selectedOptionsList = ko.computed(function() {
return this.selectedOptions().join(",");
}, viewModel);
ko.applyBindings(viewModel);
Here is the jsFiddle link: http://jsfiddle.net/rupesh_kokal/AFzbY/
这是 jsFiddle 链接:http: //jsfiddle.net/rupesh_kokal/AFzbY/
回答by nemesv
You can achieve the 1. version with using an extra span
for the text:
您可以使用额外span
的文本来实现 1. 版本:
<label>
<input type="checkbox" data-bind="value: $data.optionvalue,
checked: $parent.selectedOptions" />
<span data-bind="text: $data.optiontext"/>
</label>
Or the 2. version with using the attr bindingto set the id
and the for
attribute:
或使用attr 绑定设置id
和for
属性的 2. 版本:
<input type="checkbox" data-bind="value: $data.optionvalue,
checked: $parent.selectedOptions, attr: { id: optiontext}" />
<label data-bind="text: $data.optiontext, attr: {for: optiontext}" />
回答by Jesper Jensen
Yo can even get the binding to drop the extra span-element, by using Knockouts comment-binding syntax:
你甚至可以通过使用 Knockouts 注释绑定语法获得删除额外跨度元素的绑定:
<label>
<input type="checkbox" data-bind="value: $data.optionvalue,
checked: $parent.selectedOptions" />
<!-- ko text: $data.optiontext --><!-- /ko --></label>
This will prevent the checkbox and the span from breaking up on two lines, if used in narrow spaces.
如果在狭窄的空间中使用,这将防止复选框和跨度在两行上分开。