我使用的是jQuery 1.9.1、jQM 1.3和knockout 2.2.1。
我的html如下:
<div data-role="page" id="coloursView">
<div data-role="content">
<fieldset data-role="controlgroup">
<legend>Colour:</legend>
<input type="radio" name="colours" data-bind="checked: colour" id="radio-1" value="1" />
<label for="radio-1">Red</label>
<input type="radio" name="colours" data-bind="checked: colour" id="radio-2" value="2" />
<label for="radio-2">Blue</label>
<input type="radio" name="colours" data-bind="checked: colour" id="radio-3" value="3" />
<label for="radio-3">Green</label>
</fieldset>
</div><!--/content -->
</div><!--/page -->我的视图模型也非常简单:
function ColoursViewModel() {
this.template = "coloursView";
this.colour = ko.observable("1");
this.label = ko.observable(); // custom binding
}现在,我想要获取所选颜色的描述,而不是值。在我看来,我需要一个自定义绑定,就像这样:
ko.bindingHandlers.label = {
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$("radio", element).filter(function(el) { return $(el).text() === value; }).prop("checked", "checked");
}
};但是我无法获取文本的相关标签的文本。
有人能帮上忙吗?提前感谢
发布于 2013-04-26 07:24:13
很抱歉我自己回答,但我想我知道了。至少用于无线电输入的。
现在,我在fieldset级别有了一个自定义绑定处理程序,以尽可能保持标记的整洁和可读性:
<fieldset data-role="controlgroup" id="front-colours" data-bind="frontColourLabel: frontColour">
<legend>Front Colour: <span data-bind="text: frontColourDescription"></span> (Value: <span data-bind="text: frontColour"></span>)</legend>
<input type="radio" name="front-colours" data-bind="checked: frontColour" id="fc-radio-1" value="red" />
<label for="fc-radio-1">Red</label>
<input type="radio" name="front-colours" data-bind="checked: frontColour" id="fc-radio-2" value="blue" />
<label for="fc-radio-2">Blue</label>
<input type="radio" name="front-colours" data-bind="checked: frontColour" id="fc-radio-3" value="green" />
<label for="fc-radio-3">Green</label>
</fieldset>这是我打开的绑定处理程序:
ko.bindingHandlers.frontColourLabel = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
ko.utils.unwrapObservable(valueAccessor());
var id = $('input:radio[name='+element.id+']:checked').prop("id");
var radioText = $('label[for=' + id + ']').text();
viewModel.frontColourDescription(radioText);
}
};这里唯一棘手的部分是fieldset的id等于电台组的名称,因为很容易过滤出我想要寻址的电台组。
工作示例: http://jsfiddle.net/h7Bmb/1/
我现在尝试让checkbox部分正常工作。有人能帮上忙吗?
发布于 2013-04-23 08:02:10
更新
这是另一种仅查找:checked项并删除文本中空格的方法。
复选框
$('input[type=checkbox]').each(function () {
if ($(this).is(':checked')) {
var checkbox = $(this).prev('label').text();
alert('Checkbox: ' + checkbox.replace(/\s+/g, ' '));
}
});无线电
$('input[type=radio]').each(function () {
if ($(this).is(':checked')) {
var radio = $(this).prev('label').text();
alert('Radio: ' + radio.replace(/\s+/g, ' '));
}
});复选框
$('div.ui-checkbox').find('span.ui-btn-text').text();无线电
$('div.ui-radio').find('span.ui-btn-text').text();https://stackoverflow.com/questions/16157506
复制相似问题