当页面的一部分加载了动态创建的按钮时,我无法激活相关的 JavaScript/jQuery 事件。 我该如何解决这个问题?解决此问题的最佳方法是什么?
这是基于我在真实案例中遇到的问题。
我有这个函数来调用 php 函数,以使用 Ajax 在页面中生成新的动态创建分页部分。
function loadData(page){
$.ajax({
type: "POST",
url: ".../get_Scorewithagination.php",
data: 'page='+page+'&testID='+testID+'&testDate='+testDate+'&empPass='+empPass+'&courseCode='+courseCode,
success: function(msg){
$('#testInfo').empty();
$(document).ajaxComplete(function(event, request, settings){
loading_hide();
$("#resultBox").html(msg); to #resultBox
});
$('.iconpoint_orange').click(function() {
btnNames = $(this).attr("name").split("_");
$.post('.../getInfo.php', {testresult: btnNames[1]}, ShowTestInfo);
});
// Collapse row on delete
$('.iconpoint_blue').click(function() {
alert();
rowName = this.name;
rowID = '#' + rowName;
$(this).closest('tr').children('td').addClass("row_hover");
$("#dialog_confirm").html("Are you sure you want to delete this?");
$("#dialog_confirm").dialog({
buttons : {
"Delete" : function() {
$(rowID).closest('tr').animate({opacity: 0},500).slideUp(300);
setTimeout(function() {$(rowID).closest('tr').empty().remove();} ,3000);
$(this).dialog("close");
},
"Cancel" : function() {
$(rowID).closest('tr').children('td').removeClass("row_hover");
$(this).dialog("close");
}
}
});
$("#dialog_confirm").dialog("open"); // Show dialog box
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
$('#testInfo').html("<br\>Status: " + textStatus +"<br\>Error: " + errorThrown);
$('#testInfo').addClass("errorRed");
}
});//$.ajax() END
}//loadData(page) END
但问题是这两个按钮
.iconpoint_blue
和
.iconpoint_orange
在我用 Ajax 调用的 php 文件动态生成行后,无法调用响应。
我知道 Ajax 返回的 html 代码不会在文档完成的开头被 JavaScript 扫描,因为它是稍后完成的,因此,我动态创建的按钮即使是正确的选择器也不会响应该功能#
。
我想要动态生成的按钮与每个记录的现有函数选择器,将能够回调页面加载时加载的函数?
最佳答案
将函数绑定(bind)到父元素。例如,使用以下 HTML:
<div class='wrapper'>
<a href='#' class='click_here'>click here</a>
</div>
您可以使用以下 JavaScript:
$('.wrapper').on( 'click', '.click_here', function() {
$(this).after('<a href="#" class="or_here">or here</a>');
});
$('.wrapper').on( 'click', '.or_here', function() {
$(this).remove();
});
Here是一个 jsFiddle。
关于javascript - 如何在页面加载后动态生成的 DOM 对象上触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17428400/