我创建了一个下拉菜单,当按下按钮时该菜单会动态填充,但是直到多次单击该按钮后,内容才会显示出来,一旦显示就可以了。 HTML是:
$('#btnGroupDrop1').on( 'click', $('#availableVans'), function() {
getAvailableVans();
});
function getAvailableVans() {
$.ajax({
url: "${ctx}/str/getDeliveryVans.jx?${_csrf.parameterName}=${_csrf.token}",
type: 'POST',
contentType: 'application/json',
success: function(data) {
var buttonHtml = '<button id="buttonGroupDrop1" type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> Add new list for:</button>\n';
var divHeader = '<div id="availableVans" class="dropdown-menu" aria-labelledby="buttonGroupDrop1">\n';
var vanList = "";
$.each( data.vans ,function( idx, van ){
var userVan = '<a class="dropdown-item newListBtn" data-id="' + van.id + '" data-color="' + van.strelColor + '" data-user="' + van.username + '">' + van.username + '</a>';
vanList = vanList + userVan + "\n";
});
var allVans = '<a class="dropdown-item newListBtn" data-id="0" data-color="" data-user="ALL VANS">ALL VANS</a>\n';
var divFooter = '</div>';
$('#buttonGroup').html( buttonHtml + divHeader + vanList + allVans + divFooter);
},
error: function(data,status,er) {
alert("Failure to retrieve list of vans");
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="buttonGroup" class="btn-group" role="group">
<button id="btnGroupDrop1" type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
Add new list for:
</button>
<div id="availableVans" class="dropdown-menu" aria-labelledby="btnGroupDrop1">
<c:forEach var="van" items="${map.vans}" varStatus="status">
<a class="dropdown-item newListBtn" data-id="${van.id}" data-color="${van.strelColor}" data-user="${van.username}">${van.username}</a>
</c:forEach>
<a class="dropdown-item newListBtn" data-id="0" data-color="" data-user="">ALL VANS</a>
</div>
</div>
答案 0 :(得分:0)
单击后应为选择器,并且您编写了一个元素 更改此代码
$('#btnGroupDrop1').on( 'click', $('#availableVans'), function() {
getAvailableVans();
});
到
$(document).on( 'click', '#btnGroupDrop1', function() {
getAvailableVans();
});