我正在使用 Ajax 调用 Web 服务方法来检索数据集并尝试使用 BS 列表组显示它。
我尝试了在循环内生成单个列表项的不同方法,但似乎都不起作用。这是最新的尝试。
HTML:
<div class="list-group" id="divLg">
</div>
Ajax成功部分:
}).done(function (result) {
if (!result || result.d === "") {
}
else {
jResult = JSON.parse(result.d);
$.each(jResult, function (index, curr) {
var title = curr.Title;
var postingText = curr.PostingText;
var postDate = curr.StartDate;
// First attempt, totally off!
//$('<a>', { class: 'list-group-item list-group-item-action' + (index == 0 ? ' active' : '') })
// .append($('<div/>', { class: 'd-flex w-100 justify-content-between' })
// .append($('<h6/>', { class: 'mb-1' }, { id: 'spnTitle' + index }).append(document.createTextNode(title)))
// .append($('span', { id: 'spnPostStartDate' + index }).append(document.createTextNode(postDate))))
// .append($('p', { id: 'pDescr' + index }, { class: 'mb-1' }).append(document.createTextNode(postingText)))
// .append($('span').append(document.createTextNode('some text here')))
// .appendTo($('#divLg'));
// Last attempt
var jLink = '<a id="jLink' + index + '" href="#" class="list-group-item list-group-item-action jLink' + index + '" aria-current="true"></a>';
var jDiv = '<div id="jDiv' + index + '" class="d-flex w-100 justify-content-between jDiv' + index + '"></div>';
var hdr = '<h6 class="mb-1 jHdr' + index + '"><span id="spnTitle' + index + '">' + title + '</span></h6>';
var spnSD = '<small><span id="spnPostStartDate' + index + '" class="jSD' + index + '">' + postDate + '</span></small>';
var pJob = '<p class="mb-1">' + postingText + '</p>';
var spnMoreInfo = '<span>Posting URL goes here.</span>';
$jLink = $(jLink);
$jDiv = $(jDiv);
$hdr = $(hdr);
$spnSD = $(spnSD);
$pJob = $(pJob);
$spnMoreInfo = $(spnMoreInfo);
$('#jDiv' + index).append($(hdr));
$('#jDiv' + index).append($(spnSD));
$('#jLink' + index).append($(jDiv));
$('#jLink' + index).append($(pJob));
$('#jLink' + index).append($(spnMoreInfo));
$('#divLg').append($(jLink));
});
}
}).fail(function (jqXHR, textStatus, errorThrown) {
//alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
});
我想最终得到:
<div id="divLg" class="list-group">
<a href="#" class="list-group-item list-group-item-action active" aria-current="true">
<div class="d-flex w-100 justify-content-between">
<h6 class="mb-1">Some Title</h6>
<small>10/11/2024</small>
</div>
<p class="mb-1">Some placeholder content in a paragraph.</p>
<small>And some small print.</small>
</a>
<a ...>
...
</a>
</div>
在将
$('#jDiv' + index)
添加到 DOM 之前,您不能使用 $jDiv
。
但是由于您要附加的 div 位于变量中,因此您可以使用它而不是搜索 DOM。
$jDiv.append($hdr, $spnSD);
$jLink.append($jDiv, $pJob, $spnMoreInfo);
$("#divLg").append($jLink);
.append()
也可以给定多个参数,它会附加所有参数,而不是重复调用它。