gpt4 book ai didi

jquery - ajax 调用完成后创建自定义事件

转载 作者:行者123 更新时间:2023-12-01 07:44:56 24 4
gpt4 key购买 nike

我正在尝试在完成 $post ajax 调用后创建自定义事件监听器。这是我的代码:

$.post( url, data, function(response) {
//Fadeout the ajax loder image
$('#ajax-image').fadeOut();

//Insert the Response (HTML Format) in a hidden div
$('#scpanels').html(response).fadeIn();

// Create an event so that other scripts can interact
$.response.trigger('MyCustomEvent');
});

然后,在其他js文件中:

$( document ).on( 'MyCustomEvent', function() {

//Do stuffs when that AJAX call finishes

});

这根本不起作用。抱歉,我是 jQuery 新手,这可能超出了我目前的能力。

谢谢

最佳答案

您需要做的就是在文档上触发它,而不是在响应上触发它

像这样:

$.post( url, data, function(response) {
//Fadeout the ajax loder image
$('#ajax-image').fadeOut();

//Insert the Response (HTML Format) in a hidden div
$('#scpanels').html(response).fadeIn();

// Create an event so that other scripts can interact
$(document).trigger('MyCustomEvent'); // only change here
});

然后它应该可以工作

更新:没有ajax的简单示例。我只是想知道这如何在多个js文件上工作,因为我以前从未这样做过,这是你问题的一部分。所以我只是创建了一个简单的例子也许对你有帮助。

在目录中创建一个包含以下内容的 index.html 文件:

<!doctype html>
<html lang="en">
<head>
</head>
<body>
<div class="click-me">click-me</div>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="./script-1.js"></script>
<script src="./script-2.js"></script>
</body>
</html>

然后在同一个目录下创建两个js文件。一个 script-1.js

$('.click-me').on('click', function(){
$(document).trigger('MyCustomEvent');
});

和另一个script-2.js

$( document ).on('MyCustomEvent', function() {
alert('it works');
});

请告诉我它是否适合您。

关于jquery - ajax 调用完成后创建自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40069527/

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