【发布时间】:2014-06-03 07:04:07
【问题描述】:
我有一个模态对话框 (Bootstrap),其中有一个列表组,其中包含自定义列表组项(在从我的服务器添加数据后使用 append 循环填充)。
在每个列表组项中,我都有一个复选框,用于“选择”结果。在填充项目时,我将 JQuery click 事件连接到相应的复选框:
// 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 个“centroid-checkbox-XXXXX”复选框。我在这里做错了什么?
【问题讨论】:
-
$函数永远不会返回undefined。 -
为什么你把 $('#search-results').append( 外部 dom 准备好了?
-
我猜
$(document).ready(function () {中的包装是没用的。 -
@dystroy 如果在执行时没有 $('#search-results') 元素会发生什么?如果元素在脚本之后渲染,那会导致错误吗?
-
不是错误,不会有任何作用。由于它有效(或者 OP 会这么说),我想当 DOM 已经准备好时调用整个代码。但这只是一个猜测。无论如何,代码似乎与您注意到的点不一致。
标签: javascript jquery twitter-bootstrap checkbox jquery-selectors