javascript - 为什么在 jQuery 单击事件触发我的 es6 类函数之一后,我的其他类函数和变量变得未定义

标签 javascript jquery undefined-reference jquery-events es6-class

我正在运行 es6 类函数来重新设计我的身份验证页面。当用户单击“立即注册”链接时,showRegisterSection 函数应该运行,以便它从身份验证页面的登录部分切换到注册部分。但是,问题是,当我尝试访问在构造函数和类的其他函数中初始化的局部变量以执行一些重新设计任务时,浏览器控制台返回:

"functionName is not a function"

对于函数和

"undefined"

变量值。

我尝试过不同的功能并在网上搜索解决方案但无济于事。此外,如果我复制函数内的代码并将它们粘贴到我的事件处理程序 showRegisterSection 中,或者在事件处理程序内重新分配变量,一切都会按预期进行。

请记住,设计登录部分的第一个函数称为, ShowLoginSection 工作得很好,并且不是从事件中调用的。它也是设置调用 showRegisterFunction 的点击事件的函数。

代码如下:

    removeElement,
    insert_custom_social_login_before_target_Element
 } from './util';

export default class GulaitAuth{
    //if the isLogin variable is true, then we set up the login part else, we set up the register part
    constructor(isLoginSection, loginForm){
        this._isLoginSection = isLoginSection;
        this._loginForm = loginForm;
        this.initLocalVars();
    }

    /**
     * This function initializes local variables to their supposed values
     * except those passed in on creation of class obj.
     * This is due to an unknown issue where variables simply get reset  to undefined
     */
    initLocalVars(){
        this._loginDiv = document.querySelector('.woocommerce #customer_login').firstElementChild;
        this._registerDiv = document.querySelector('.woocommerce #customer_login').lastElementChild;
        this._myAccHeader = document.querySelector( '.woocommerce-account #main #contents header h2' );
        this._socialLoginContainer = document.querySelector( '#customer_login .apsl-login-networks.theme-2.clearfix' );
        this._authPageLoginForm = document.querySelector( '.woocommerce-page #customer_login form.login' );
    }

    setupAuthPage(){
        //setup the authentication page
        //css styles for Auth page if the loginForm exists on the page
        if( this._loginForm ){
            //remove header "MY ACCOUNT" from DOM
            removeElement(this._myAccHeader);

            //center the auth div
            jQuery('body.page-id-29 .container .row.sidebar-row').css('text-align', 'center');

            //style the Auth div - container
            jQuery('.woocommerce-account #contents').css({
                'max-width' : '38.5em',
                'display': 'inline-block',
                'text-align': 'initial',
                'padding': '1.5em',
                'border-top' : '.15em solid #DF1F26e5'
            });

            if( this._isLoginSection ){
                this.showLoginSection();
            } else {
                this.showRegisterSection();
            }

        }
    }

    /**
     * Show Login or Register Section based on _isLoginSection variable
     */
    showLoginOrRegister(){
        if(this._isLoginSection){
            //edit the login div
            jQuery(this._loginDiv).css( {'min-width' : '100%', 'padding' : '0', 'display' : 'block'} );

            //hide the register div
            jQuery(this._registerDiv).css( 'display', 'none' );
        } else {
            //hide the login div
            jQuery(this._loginDiv).css( 'display', 'none' );

            //edit the register div
            jQuery(this._registerDiv).css( {'min-width' : '100%', 'padding' : '0', 'display' : 'block'} );
        }

    }

    showLoginSection(){
        //show loginsection
        this.showLoginOrRegister();

        //remove full width on checkbox
        jQuery('.woocommerce #customer_login form.login input[type="checkbox"]').css('min-width', '0 !important');

        //remove extra spacing to the right
        jQuery('.woocommerce-account #main #contents .type-page').css('padding', '0');

        //row containing login and register forms is slightly pushed to the left with margin
        //this makes styling difficult as it has wierd positioning
        jQuery('div#customer_login.row').css('margin', '0');

        //remove extra space after the 'lost password?' section
        jQuery('.entry .entry-content .entry-summary').css('margin-bottom', '0');

        //remove login form margin
        jQuery('.woocommerce-page #customer_login form.login').css('margin', '0');

        //edit the login text
        jQuery('.woocommerce #customer_login h2')
        .css( { 
            'border-bottom' : '0',
            'margin-bottom' : '0',
            'padding-bottom' : '0.2em'
        } )
        .text('')
        .append(
            '<span id="login-text">Login</span><span id="or-text"> Or </span><span id="register-text">Register</span>'
        );

        jQuery('#or-text, #register-text').css( {
            'opacity' : '.2',
            'font-size' : '16px',
            'word-spacing' : '.12em',
            'font-weight' : '450'
        } );


        //Insert REGISTRATION Link after 'lost password' section
        jQuery("<p style='margin-top: 2em;'>Don't have an account? <strong id='register-link'><a href='#'>Register now</a></strong></p>")
        .insertAfter("#customer_login .login p.lost_password")
        .children("#register-link").click( this.showRegisterSection );

        //add an eventListener on the register link
        //jQuery('#register-link');

        //redesign the input form input fields
        jQuery('#customer_login .login .form-row.form-row-wide input').css( {
            'border' : '1px solid #ccc',
            'background' : 'white'
        } );

        //fb color = #1c74bc

        //Delete original social login and replace with custom version in the 
        //prefered position
        this.relocateSocialLogin();
    }

    showRegisterSection(){
        console.log('Register Link clicked');

        //set isLogin to false in order to show content as designed for the register form
        this._isLoginSection = false;

        //This function initializes local variables to their supposed values except
        //those passed in on creation of class obj. 
        //This is due to an unknown issue where variables simply get reset to undefined
        this.initLocalVars();

        //show register section
        //hide the login div
        jQuery(this._loginDiv).css( 'display', 'none' );

        //edit the register div
        jQuery(this._registerDiv).css( {'min-width' : '100%', 'padding' : '0', 'display' : 'block'} );
    }

    /**
     * Delete original social login and replace with custom version in the 
     * prefered position to fit design
     */
    relocateSocialLogin(){
        //Delete existing social login
        this._socialLoginContainer.parentNode.removeChild( this._socialLoginContainer );

        //Insert custom social login just before login form on auth page = my-account page
        insert_custom_social_login_before_target_Element( this._authPageLoginForm );

    }

}

最佳答案

您必须将 this 引用保留在 showLoginSection() 内定义的点击处理程序中

如所写:.children("#register-link").click( showRegisterSection );

使用箭头函数:.children("#register-link").click( e => this.showRegisterSection(e)); 然后,showLoginSection() 内任何 thisthis 引用都将被保留。 (我们的身份验证实例)

替代方案是.bind()的变体 因此,要么 .children("#register-link").click( this.showRegisterSection.bind(this));showLoginSection()

或者constructor(isLoginSection, loginForm){内的this.showRegisterSection = this.showRegisterSection.bind(this);

您必须对将用作事件处理程序的所有函数执行此操作,或者在函数不作为 GulaitAuth 类的方法调用的其他情况下执行此操作。

关于javascript - 为什么在 jQuery 单击事件触发我的 es6 类函数之一后,我的其他类函数和变量变得未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59894403/

相关文章:

javascript - 更改触摸 :TouchList is not a property?

jquery - Django Rest Framework CSRF token 失败

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

c++ - C++简单项目中的 undefined reference

javascript - jQuery,如何使点击函数与数组一起使用以根据 id 切换 div?

javascript - 在 Jinja2 模板中使用 include 语句传递变量

javascript - 与同步 ajax 调用的返回值混淆

javascript - 有没有办法给每个 div 一个唯一的 id 而不必每次都输入它?

c - as400 ILE C 全局变量多重重定义

javascript - 自动注册电话号码格式 (xxx) xxx-xxxx