[英]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.