我有一个模态对话框(Bootstrap),其中有一个list-group与自定义list-group-items(通过循环使用append从我的服务器添加数据后填充)。
在每个list-group-item中,我都有一个Checkbox,用于"选择"结果。在填充项目时,我将JQuery单击事件连接到相应的Checkbox:
// Add to search results
$('#search-results').append(
'<a id="centroid-list-item-' + featureAttrs['ObjectID'] + '" href="\#"' + 'class="list-group-item" style="outline: 0">' +
'<table style="background: transparent">' +
'<tr>' +
'<td>' +
'<input id="centroid-checkbox-' + featureAttrs['ObjectID'] + '" type="checkbox" value=""> ' +
'</td>' +
'<td>' +
'<h4 class="list-group-item-heading">' +
featureAttrs['UNIQUEID'] +
'</h4>' +
'<p id="centroid-item-text-' + featureAttrs['ObjectID'] + '"' + 'class="list-group-item-text">' +
featureAttrs['NAME'] +
'</p>' +
'</td>' +
'</tr>' +
'</table>' +
'</a>'
);
// When the DOM is ready, add event
$(document).ready(function () {
$('#centroid-checkbox-' + featureAttrs['ObjectID']).click(function (event) {
var objectId = $(this).attr('id').replace(/^D+/g, '');
console.log(objectId + " was clicked");
if ($(this).is(':checked')) {
// Enable the 'Set Target' button
$('#btn-set-target').removeAttr('disabled');
// Disable all other choices
$('[id^="centroid-checkbox-"]').each(function (event) {
console.log("Picked up values for checkboxes");
if ($(this).attr('id') != ('centroid-checkbox-' + objectId)) {
$(this).attr('disabled', true);
}
});
}
else {
$('#btn-set-target').attr('disabled', 'disabled');
// Enable all text boxes
$('[id^="centroid-checkbox-"]').each(function () {
if (this.attr('id') !== ('centroid-checkbox-' + objectId)) {
this.removeAttr('disabled');
}
});
}
});
});
我遇到的问题是,当我调用$('[id^="centroid-checkbox-"]')
它返回未定义。然而,当它被调用时,大约有30个"质心-checkbox- xxxxx"复选框。我哪里做错了?
$
函数永远不会返回undefined
。
但this
在回调你传递给each
是一个元素,而不是一个jQuery对象。
这意味着你必须使用this.id
而不是this.attr('id')
和$(this).removeAttr('disabled')
而不是this.removeAttr('disabled')
(你可能想要this.disabled=false
或$(this).prop('disabled', false)
)。
objecd永远不会被定义,因为您需要将用于replace()的正则表达式括起来:
var objectId = $(this).attr('id').replace(/^D+/g, '');
应:var objectId = $(this).attr('id').replace('/^D+/g', '');
演示:http://jsfiddle.net/4fUvn/8/