重新捕获对包含数据回调回调函数中的DOM元素的局部变量的访问

时间:2018-10-11 14:39:04

标签: javascript recaptcha

在我的网站上,我有google reCaptcha组件,该组件使我可以在属性“数据回调”中指定一个回调函数。

这是我的html文件:

public class CFactory {

      public static C from(String s1, String s2) {
        C c;
        ...
        ...

        return c;
       }

       public static C from(ResultSet resultSet) throws SQLException {
         C c;
         ....
         ...
         return c; 
         } 
}
@Builder
@Getter //lombok
public class C extends A{

        private final String varA;
        private final String varB;
        private final String varC;

        ....
        ....

}

除我无法从回调函数“ successCallback”访问包含DOM元素的局部变量txtClientResponse之外,其他所有方法均工作正常。像var test = 1这样的局部变量,我可以使用this.test进行访问。

我试图像在Angular上一样使用“ this”传递,但没有成功。我需要一个纯JavaScript解决方案-不是角度的:

<html>
    <script src='https://www.google.com/recaptcha/api.js'></script>    
    <script type="text/javascript">

    var txtClientResponse = document.getElementById('txtClientResponse');
    var txtServerResponse = document.getElementById('txtServerResponse');

    function successCallback(value) {

        this.txtClientResponse.value = value;
        this.txtServerResponse.innerText.clear();

    }
</script>
<body>
    <div class="g-recaptcha" data-callback="successCallback" data-error-callback="errorCaptcha" data-sitekey="xxxxxx" />

    <input ID="txtClientResponse" />
    <input ID="txtServerResponse" />

</body>

1 个答案:

答案 0 :(得分:0)

我很久没有使用纯JavaScript了,因为我使用的是Angular,我忘记了带有javascript代码的script标签应该位于body标签内容的最底部,或者至少要用getElementById分配变量在document.onreadystatechange事件中。

问题在于这些行:

var txtClientResponse = document.getElementById('txtClientResponse');
var txtServerResponse = document.getElementById('txtServerResponse');

在准备就绪的HTML元素之前执行。

这是针对可能会使用Google找到此问题的用户的解决方法

<html>    
<body>
    <div class="g-recaptcha" data-callback="successCallback" data-error-callback="errorCaptcha" data-sitekey="xxxxxx" />

    <input ID="txtClientResponse" />
    <input ID="txtServerResponse" />

    <script src='https://www.google.com/recaptcha/api.js'></script>
    <script type="text/javascript">

        var txtClientResponse = document.getElementById('txtClientResponse');
        var txtServerResponse = document.getElementById('txtServerResponse');

        function successCallback(value) {

            this.txtClientResponse.value = value;
            this.txtServerResponse.innerText.clear();

        }
    </script>

</body>
</html>