内联javascript工作,但不作为参考



我有一个处理验证码的代码块。当我测试它作为内联它工作得很好。但是当我使用<script src="js.js"></script>时,它没有。我一直得到recaptcha()不是一个函数错误消息。更令人困惑的是js.js中的其余代码执行得很好。只有验证码块没有。我的理解是,SRC只是从引用位置提取数据并将其插入调用体。为什么它不起作用?此外,脚本工作作为内联包装,所以我猜脚本被插入的位置不是原因。

function recaptcha(e) {
var action = e.target.id;
grecaptcha.ready(function() {
grecaptcha.execute('12345', {action: action})
.then(function(token) {
var formData = new FormData();
formData.append("token", token);
fetch('recaptcha.php', {
method: "POST", 
body: formData
})
.then(response => response.text())
.then (action=>{
switch (action) {
case 'login':
console.log('login');
break;
case 'contact':
console.log('contact');
break;
case 'process':
console,log('process');
break;
default:
console.log('recaptcha error');
}
});
});
});
}

我猜在你试图访问recaptcha()函数的时候,你创建的js.js文件还没有被处理。您是否可以尝试将对recaptcha函数的调用包装在文档中。

// Listen for `DOMContentLoaded` event
document.addEventListener('DOMContentLoaded', (e) => {
console.log(`Document is ready!`);
recaptcha(e);
});

最新更新