如何将 JQuery 事件处理程序分配给特定事件

How to assign a JQuery event handlers to a specific event

本文关键字:事件 分配 程序 JQuery 事件处理      更新时间:2023-09-26

我有以下名为Howto的Javascript函数,它在按下按钮时执行:

function howto(){
   $('#elementtoupdate').ajaxSend(function() {
       //Code to execute
   });
   $('#elementtoupdate').ajaxComplete(function() {
       //Code to execute
   });
   $('#elementtoupdate').load('serverside/file_path.php')
}
使用 JQuery

函数分配两个 JQuery 全局 Ajax 事件处理程序,它们在启动任何 AJAX 调用时启动。然后,该函数继续并调用 JQuery .load函数,并启动全局 Ajax 事件处理程序中的任何代码。

然而,正如名称"全局"所暗示的那样,它们也是由其他Jquery AJAX调用发起的。不幸的是,这是不可取的,因为我在脚本中有其他 AJAX 调用。我需要仅在执行$('#elementtoupdate').load('serverside/file_path.php')时执行代码。

最好的方法是什么?

load本身具有非全局回调:

.load( url [, data ] [, complete(responseText, textStatus, XMLHttpRequest) ] )

因此:

$('#elementtoupdate').load('serverside/file_path.php', function() {
  // complete
});

你应该接受David Hedlund的回答。为了完整起见:

您可以更改:

function howto(){
   $('#elementtoupdate').ajaxSend(function() {
       //code to be executed before send
   });
   $('#elementtoupdate').ajaxComplete(function() {
       //code to be executed after completed
   });
   $('#elementtoupdate').load('serverside/file_path.php')
}

自:

function howto(){
    //code to be executed before send
    $('#elementtoupdate').load('serverside/file_path.php', function(){
        //code to be executed after completed
    })
}