【问题标题】:Why can't my post functions access a variable above it?为什么我的 post 函数不能访问它上面的变量?
【发布时间】:2016-11-04 23:59:34
【问题描述】:

我试图弄清楚为什么以下代码末尾的 post 函数无法访问 userID 变量(我假设这是一个范围问题,因为在函数返回正确值之前立即记录 userId) .

    $.get("/set_languages_user", function(res) {
    console.log(res)

    if ( res.length === 0 ) {

        var getUserInfo = $.get('/set_user', function(res){

            var langConfirmSource = $('#language-confirmation-template').html();
            var langConfirmCompiled = Handlebars.compile(langConfirmSource);
            var langConfirmTemplate = langConfirmCompiled(res)
            $('body').append(langConfirmTemplate)
            $('html').toggleClass('disable_scrolling')

            var userId = res.id
            var native_language = res.native_language
            var learning_language = res.learning_language

            $(document).on('submit', '#language_confirmation', function(e){

                e.preventDefault()

                // prevent user from continuing if they haven't checked that they agree to the term's of use
                if ( $('#touCheck').is(':checked')) {
                    console.log('checked!!!')

                    // this function finds the ID of the User's defined languages
                    var getUserInfo = $.get('/languages.json', function(lang){ 

                        // Find the ID of the languages the User is supporting in order to submit to languages_users db
                        for (i = 0; i < lang.length; i++) {
                            if (lang[i].language === native_language) {
                                var confirmedUserNativeInt = lang[i].id
                            }
                        }

                        for (i = 0; i < lang.length; i++) {
                            if (lang[i].language === learning_language) {
                                var confirmedUserLearningInt = lang[i].id
                            }
                        }

                        console.log(confirmedUserNativeInt)
                        console.log(confirmedUserLearningInt)
                        console.log(userId)


                        // creates a new instance in languages_user for the learningLanguage (level 1)
                        $.post( "/languages_users", { languages_user:{ language_id: confirmedUserLearningInt, user_id: userId, level: 1 }})

                        // creates a new instance in languages_user for the nativelanguage (level 5)
                        $.post( "/languages_users", { languages_user:{ language_id: confirmedUserNativeInt, user_id: userId, level: 5 } })

                        $('.signon_language_confirmation').remove()
                        $('html').toggleClass('disable_scrolling')
                    });

                } else {
                    console.log('not checked!!!')

                    $('.wrapper_tou_signup').append('<p class="message_form_error">You must agree to Lexody\'s Terms of Use to continue.</p>')
                }
            })
        });
    }
})

这是正在渲染的车把模板:

<script id="language-confirmation-template" type="text/x-handlebars-template">
<div class="signon_language_confirmation">

    <p class="title_langconf">Welcome to</p>

    <img src="">
    <div class="wrapper_form_dark language_confirmation_form wrapper_form_sign_on">
        <form id="language_confirmation">
            <div class="form_section">
                <div class="wrapper_input col_16_of_16">
                    <p>I speak {{native_language}} <svg class="icon_standard"><use xlink:href="#{{native_language}}"/></svg></p>
                    <p>I am learning {{learning_language}} <svg class="icon_standard"><use xlink:href="#{{learning_language}}"/></svg></p>

                    <div class="wrapper_tou_signup">
                        <p><input type="checkbox" name="tou" value="agree" id="touCheck"> I agree to Lexody's <a href="#">terms of use</a>.</p>
                    </div>
                    <div class="submit_cancel">
                        <input type="submit" value="Submit" class="btn_primary submit">
                    </div>
                </div> 
            </div>
        </form>
    </div>
</div>

当我提交时,我收到“Uncaught ReferenceError: userId is not defined(...)”。如何使这些函数可以访问该变量,为什么该变量无法访问,而其他变量('confirmedUserLearningInt' 和 'confirmedUserNativeInt')可以访问?

提前致谢。

【问题讨论】:

    标签: javascript jquery handlebars.js


    【解决方案1】:

    你还没有在 post 方法可以到达的地方声明 var,正如你在代码中看到的那样,var 位于 for 循环内的 if 语句中,你应该在 for 循环之前声明 var,如下所示:

          $.get("/set_languages_user", function(res) {
            console.log(res)
        
            if ( res.length === 0 ) {
        
                var getUserInfo = $.get('/set_user', function(res){
        
                    var langConfirmSource = $('#language-confirmation-template').html();
                    var langConfirmCompiled = Handlebars.compile(langConfirmSource);
                    var langConfirmTemplate = langConfirmCompiled(res)
                    $('body').append(langConfirmTemplate)
                    $('html').toggleClass('disable_scrolling')
        
                    var userId = res.id
                    var native_language = res.native_language
                    var learning_language = res.learning_language
        
                    $(document).on('submit', '#language_confirmation', function(e){
        
                        e.preventDefault()
        
                        // prevent user from continuing if they haven't checked that they agree to the term's of use
                        if ( $('#touCheck').is(':checked')) {
                            console.log('checked!!!')
        
                            // this function finds the ID of the User's defined languages
                            var getUserInfo = $.get('/languages.json', function(lang){ 
        
                                // Find the ID of the languages the User is supporting in order to submit to languages_users db
                                var confirmedUserNativeInt; //<<<<<<<<<<<<<<
                                for (i = 0; i < lang.length; i++) {
                                    if (lang[i].language === native_language) {
                                        confirmedUserNativeInt = lang[i].id
                                    }
                                }
                                var confirmedUserLearningInt;//<<<<<<<<<<<<<<<<
                                for (i = 0; i < lang.length; i++) {
                                    if (lang[i].language === learning_language) {
                                        confirmedUserLearningInt = lang[i].id
                                    }
                                }
        
                                console.log(confirmedUserNativeInt)
                                console.log(confirmedUserLearningInt)
                                console.log(userId)
        
        
                                // creates a new instance in languages_user for the learningLanguage (level 1)
                                $.post( "/languages_users", { languages_user:{ language_id: confirmedUserLearningInt, user_id: userId, level: 1 }})
        
                                // creates a new instance in languages_user for the nativelanguage (level 5)
                                $.post( "/languages_users", { languages_user:{ language_id: confirmedUserNativeInt, user_id: userId, level: 5 } })
        
                                $('.signon_language_confirmation').remove()
                                $('html').toggleClass('disable_scrolling')
                            });
        
                        } else {
                            console.log('not checked!!!')
        
                            $('.wrapper_tou_signup').append('<p class="message_form_error">You must agree to Lexody\'s Terms of Use to continue.</p>')
                        }
                    })
                });
            }
        })

    【讨论】:

    • 谢谢,但这两个变量可以在 post 函数中访问。是 userId 变量不起作用。
    猜你喜欢
    • 2014-10-05
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多