动态附加下拉列表中显示的下拉锚标记后,单击事件不会触发 - 似乎我需要在.append
之后重新绑定点击处理程序,或者我是否需要包装点击处理程序在一个函数?
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(function () {
ajax_call("database");
$body = $("body");
$(document).on({
ajaxStart: function() { $body.addClass("loading"); },
ajaxStop: function() { $body.removeClass("loading"); }
});
$(".dropdown-menu a").on("click", function () {
var selText = $(this).text();
ajax_call(selText);
});
function ajax_call($aff){
$.ajax({
url: 'fill_crosstab.php',
data: {action:$aff},
dataType: 'json',
success: function(data){
$('#frame .table tbody').empty();
if ($aff == "database") {
$.each(data, function(key, val) {
$('.dropdown-menu').append("<a class='dropdown-item' href='javascript:;'>" + val.Affiliation + "</a>");
});
} else {
$.each(data, function(key, val) {
$('#frame .table tbody').append("<tr><td>" + val.LAST + "</td><td>" + val.FIRST + "</td><td>" + val.MDC + "</td><td>" + val.RADIO + "</td><td>" + val.ePCR + "</td><td>" + val.Firehouse + "</td></tr>");
});
}
}
//dd_call();
});
};
});
</script>
HTML:
<div class="btn-group">
<button type="button" class="btn btn-primary">Affiliations</button>
<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Toggle Dropdown</span>
</button>
<div class="dropdown-menu">
</div>
</div>
答案 0 :(得分:2)
您正在尝试将click事件绑定到尚不存在的元素。当你的ajax请求成功响应时,你应该绑定该事件。
function ajax_call($aff){
$.ajax({
url: 'fill_crosstab.php',
data: {action:$aff},
dataType: 'json',
success: function(data){
$('#frame .table tbody').empty();
if ($aff == "database") {
$.each(data, function(key, val) {
$('.dropdown-menu').append("<a class='dropdown-item' href='javascript:;'>" + val.Affiliation + "</a>");
});
// Bind the event now, after the html element has bend created.
$(".dropdown-menu a").on("click", function () {
var selText = $(this).text();
ajax_call(selText);
});
} else {
$.each(data, function(key, val) {
$('#frame .table tbody').append("<tr><td>" + val.LAST + "</td><td>" + val.FIRST + "</td><td>" + val.MDC + "</td><td>" + val.RADIO + "</td><td>" + val.ePCR + "</td><td>" + val.Firehouse + "</td></tr>");
});
}
}
});
};
答案 1 :(得分:1)
应该是这样的:
$(".dropdown-menu").on("click", "a", function () {
var selText = $(this).text();
ajax_call(selText);
});
将动态元素作为第二个参数,请参阅更多详细信息here。