尝试将 hCaptcha 添加到我的网站,但不理解这段 javascript 代码

Ski*_*o83 0 html javascript forms

JavaScript 并不是我的强项。我已经在后端使用了用于验证码的 php,但我希望能够使用 JS 验证表单,以防止用户在验证码尚未完成时发送表单。

这是 hcaptca 网站提供的示例: https://medium.com/@hCaptcha/using-hcaptcha-with-php-fc31884aa9ea

这是他们作为示例给出的 JS 代码。

$("form").submit(function(event) {

   var hcaptchaVal = $('[name=h-captcha-response]').value;
   if (hcaptchaVal === "") {
      event.preventDefault();
      alert("Please complete the hCaptcha");
   }
});
Run Code Online (Sandbox Code Playgroud)

我不是 100% 确定,但这似乎是 Jquery,而我的网站不使用 Jquery。所以我需要一个普通的 JS 解决方案。

Thi*_*sté 5

让我尝试解释一下:

$("form").submit(function(event) { }
// When the form is submitted
Run Code Online (Sandbox Code Playgroud)
var hcaptchaVal = $('[name=h-captcha-response]').value;
// Retrieve the value of the captcha (= the value of an HTML element with the tag name="h-captcha-response"
Run Code Online (Sandbox Code Playgroud)
if (hcaptchaVal === "") {
   event.preventDefault();
   alert("Please complete the Captcha");
}
// If the value of the captcha is empty, stop the form submission and alert the user
Run Code Online (Sandbox Code Playgroud)

因此,如果您正在寻找 Vanilla JS 解决方案,这并不难,您所要做的就是转换 jQuery 部分:

document.querySelector("#yourFormId").addEventListener("submit", function(event) {

   var hcaptchaVal = document.querySelector('[name="h-captcha-response"]').value;
   if (hcaptchaVal === "") {
      event.preventDefault();
      alert("Please complete the hCaptcha");
   }
});
Run Code Online (Sandbox Code Playgroud)