简体   繁体   English

延迟事件处理程序直到另一个函数完成

[英]Delaying event handler until another function is completed

We've recently implemented a 3rd party solution into our website, for which I can not directly update the code but I can add my own javascript to manipulate it.我们最近在我们的网站中实施了一个 3rd 方解决方案,为此我无法直接更新代码,但我可以添加自己的 javascript 来操作它。 This solution has a button, which triggers an AJAX request.此解决方案有一个按钮,可触发 AJAX 请求。 I would like to run some custom code of my own before that AJAX request is submitted and only submit it if my code allows it.我想在提交 AJAX 请求之前运行一些我自己的自定义代码,并且只有在我的代码允许的情况下才提交它。

Is there a way I can store the click eventhandler of that button in a variable or another function before overwriting the binding with my own function that will then trigger the original eventhandler function once mine has completed?有没有一种方法可以在用我自己的函数覆盖绑定之前将该按钮的单击事件处理程序存储在变量或其他函数中,然后在我完成后触发原始事件处理程序函数?

Hope that's clear...希望这很清楚...

EDIT: The click handler is added in the 3rd parties solution like so, fairly standard really.编辑:点击处理程序像这样添加到第 3 方解决方案中,确实相当标准。 However I can not directly access the controller being used so I can't just copy the function.但是我不能直接访问正在使用的控制器,所以我不能只复制函数。 Also the service provider occasionally updates their code so if I copied it, it wouldn't update when they update their code.此外,服务提供商偶尔会更新他们的代码,所以如果我复制了它,当他们更新他们的代码时它不会更新。

在此处输入图片说明

This solution has a button, which triggers an AJAX request.此解决方案有一个按钮,可触发 AJAX 请求。 I would like to run some custom code of my own before that AJAX request is submitted and only submit it if my code allows it.我想在提交 AJAX 请求之前运行一些我自己的自定义代码,并且只有在我的代码允许的情况下才提交它。

Without diving into jQuery's event handler management internals (which can change at any time), probably the simplest thing is to hide the button and replace it with your own, then trigger the button when appropriate.无需深入研究 jQuery 的事件处理程序管理内部机制(可随时更改),最简单的方法可能是隐藏按钮并将其替换为您自己的按钮,然后在适当的时候触发按钮。 See comments:看评论:

 // === The original handler $("#the-btn").on("click", function() { console.log("Original handler ran"); }); // === Your code // Get and hide the original button var btn = $("#the-btn"); btn.hide(); // Create and add replacement var newBtn = $("<input type=button>"); newBtn.val(btn.val()); newBtn.on("click", function() { console.log("Your handler starting (I'm assuming an async process)..."); setTimeout(function() { console.log("Your handler is done, triggering original"); btn.click(); }, 800); }); newBtn.insertBefore(btn);
 <input type="button" id="the-btn" value="Do Something"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM