我尝试使用 Knockout 在我的页面中添加复选框。但是那些动态添加的复选框不能通过点击它们来检查。如果我使用 jQuery 添加一个框,则生成的 HTML 与 Knockout 复选框不同。被input
包裹在另一个中<div class="ui-checkbox">
。如果不使用自定义绑定,也没有区别checkbox
。有人知道如何解决这个问题吗?
- jQuery:1.10.2
- jQuery-Mobile:1.3.2
- 淘汰赛:2.3.0
这是一个小提琴:http: //jsfiddle.net/USpX5/
HTML:
<div id="fiddle" data-bind="foreach: boxes">
<label>
<input type="checkbox" />
<span data-bind="text: name"></span>
</label>
</div>
JS:
var BoxModel = function(id, name) {
this.id = ko.observable(id);
this.name = ko.observable(name);
};
var MainModel = function()
{
this.boxes = ko.observableArray([]);
}
var main = new MainModel();
$('#add-ko').click(function() {
var i = $('#fiddle').find('input[type=checkbox]').length + 1;
main.boxes.push(new BoxModel('id'+i, 'name'+i));
});
$('#add-jqm').click(function() {
var i = $('#fiddle').find('input[type=checkbox]').length + 1;
$('#fiddle').append('<label><input type="checkbox" /><span>name'+i+'</span></label>').trigger('create');
});
// http://stackoverflow.com/a/15841271/2710739
ko.bindingHandlers.checkbox = {
init: function(element, valueAccessor) {
// set the dom element to a checkbox and initialize it (for jquerymobile)
var checkbox = $(element);
checkbox.checkboxradio();
checkbox.attr('type', 'checkbox');
},
update: function(element, valueAccessor) {
// update the checked binding, i.e., check or uncheck the checkbox
ko.bindingHandlers.checked.update(element, valueAccessor);
// and refresh the element (for jquerymobile)
var checkbox = $(element);
checkbox.checkboxradio('refresh');
}
};
ko.applyBindings(main);
生成的 HTML(从 Chrome DevTools 复制):
<div id="fiddle" data-bind="foreach: boxes">
<!-- added with ko -->
<div class="ui-checkbox">
<label data-corners="true" data-shadow="false" data-iconshadow="true" data-wrapperels="span" data-icon="checkbox-off" data-theme="c" data-mini="false" class="ui-checkbox-off ui-btn ui-btn-corner-all ui-fullsize ui-btn-icon-left ui-btn-up-c">
<span class="ui-btn-inner">
<span class="ui-btn-text">
<span data-bind="text: name">name1</span>
</span>
<span class="ui-icon ui-icon-checkbox-off ui-icon-shadow"> </span>
</span>
</label>
<div class="ui-checkbox"><!-- additional ui-checkbox class maybe causes the problem -->
<input type="checkbox" data-bind="checkbox:true">
</div>
</div>
<!-- added with jqm -->
<div class="ui-checkbox">
<label data-corners="true" data-shadow="false" data-iconshadow="true" data-wrapperels="span" data-icon="checkbox-off" data-theme="c" data-mini="false" class="ui-checkbox-off ui-btn ui-btn-corner-all ui-fullsize ui-btn-icon-left ui-btn-up-c">
<span class="ui-btn-inner">
<span class="ui-btn-text">
<span>name2</span>
</span>
<span class="ui-icon ui-icon-checkbox-off ui-icon-shadow"> </span>
</span>
</label>
<input type="checkbox">
</div>
</div>