gpt4 book ai didi

javascript - 如何在页面加载后动态生成的 DOM 对象上触发事件

转载 作者:行者123 更新时间:2023-11-29 18:22:07 25 4
gpt4 key购买 nike

当页面的一部分加载了动态创建的按钮时,我无法激活相关的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com