[英]JQuery “Attribute Starts With” Selector Undefined
我有一个模式对话框(Bootstrap),其中有一个列表组,里面有自定义列表组项目(从我的服务器添加数据后,使用append循环填充)。
在每个列表组项目中,我都有一个复选框,用于“选择”结果。 在填充项目时,我将JQuery click事件连接到相应的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个“ centroid-checkbox-XXXXX”复选框。 我在这里做错了什么?
$
函数永远不会返回undefined
。
但是, this
在你传递给回调each
一个元素,而不是一个jQuery对象。
这意味着您必须使用this.id
而不是this.attr('id')
和$(this).removeAttr('disabled')
而不是this.removeAttr('disabled')
(并且您可能想要this.disabled=false
或$(this).prop('disabled', false)
)。
objectId永远不会被定义,因为您需要用引号将正则表达式括起来用于replace():
var objectId = $(this).attr('id').replace(/^\D+/g, '');
应该:
var objectId = $(this).attr('id').replace('/^\D+/g', '');
演示: http : //jsfiddle.net/4fUvn/8/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.