jQuery提交事件绑定错误导致重复下载首个资源问题求助
解决表单提交后始终打开首次点击资源链接的问题
问题根源
你每次点击资源锚点时,都会给表单重复绑定submit事件。第一次点击后,表单上已经绑定了关联第一个资源链接的事件;第二次点击时,又新增一个关联第二个链接的事件。当提交表单时,所有绑定的事件都会触发,而闭包特性会让最早绑定的事件里的href被保留,导致每次提交都打开第一个点击的资源。
修复方案
把表单的submit事件绑定移到循环外面(只绑定一次),用一个外层变量存储当前要下载的链接,点击锚点时更新这个变量即可。
修正后的代码
jQuery(document).ready(function ($) { const anchors = Array.from( document.querySelectorAll('.page-id-17757 .elementor-element-7121f28 .elementor-widget-icon-list a') ); const modal = document.querySelector('#resources-modal'); let currentDownloadHref = ''; // 新增:存储当前要下载的链接 function getFormData($form) { var unindexed_array = $form.serializeArray(); var indexed_array = { data: {}, }; $.map(unindexed_array, function (n, i) { indexed_array.data[n['name']] = n['value']; }); return indexed_array; } function updateFormResponse(status) { if (status == 200) { $('.form-response').html('Success.'); modal.close(); $('.form-response').html(''); $('#resources-submit').prop('disabled', false); } else { $('.form-response').html('There has been an error, please refresh the page and try again'); $('#resources-submit').prop('disabled', false); // 修正:把$$改成$ } } // 把submit事件绑定移到外面,只执行一次 $('.resources-download').submit(function (e) { e.preventDefault(); e.stopImmediatePropagation(); let form = $(this); $('#resources-submit').prop('disabled', true); let formData = getFormData(form); $.ajax({ url: '/wp-content/themes/hello-elementor/raisley/resources-download.php', type: 'POST', data: formData, dataType: 'json', complete: function (data) { updateFormResponse(data.status); if (data.status == 200) { window.open(currentDownloadHref, '_blank'); // 使用外层存储的当前链接 } }, }); }); anchors.forEach((anchor) => { anchor.addEventListener('click', function (e) { e.preventDefault(); modal.showModal(); // 更新当前要下载的链接 currentDownloadHref = e.target.parentElement.href; console.log(currentDownloadHref); // 现在这里的日志和提交时的一致 }); }); });
关键改动说明
- 新增
currentDownloadHref变量,用来存储当前点击的资源链接,替代原来的闭包变量。 - 将表单的
submit事件绑定移到循环外部,避免重复绑定多个事件。 - 点击锚点时只更新
currentDownloadHref,不再每次都绑定新的提交事件。 - 修正了
updateFormResponse函数里的$$错误(应该是$)。 - 移除了内部的
downloadResource函数,直接在ajax回调里使用currentDownloadHref打开链接。
这样修改后,无论点击哪个资源,提交表单时都会打开对应的链接,不会再出现重复触发旧事件的问题。
内容的提问来源于stack exchange,提问作者jahkoora
相关产品推荐
相关产品推荐

