【问题标题】:trying to access number variable outside the function in jQuery试图在jQuery中访问函数外部的数字变量
【发布时间】:2021-09-07 04:57:21
【问题描述】:

正在创建 Stars 评级系统,我想访问评级数字并根据该数字执行操作。如何在我的 click 函数之外访问 number 变量?

$(document).ready(function () {
            $(".li").mouseover(function () {
                var current = $(this);
                $(".li").each(function (index) {
                    $(this).addClass("hovered-stars");
                    if (index == current.index()) {
                        return false;
                    }
                })
            })
            $(".li").mouseleave(function () {
                $(this).removeClass("hovered-stars");
            })
            $(".li").click(function () {
                $(".li").removeClass("clicked");
                $(".hovered-stars").addClass("clicked");
                var number = $(".clicked").length;
                $("#message").html("You rated " + number + " Stars");
            })
            console.log(number);
        })

目前无法在点击事件监听器之外打印数字变量

【问题讨论】:

    标签: javascript jquery events global-variables


    【解决方案1】:

    你需要在click函数外声明number变量,然后在click函数内重新赋值

    $(document).ready(function () {
            var number=0;
            $(".li").mouseover(function () {
                var current = $(this);
                $(".li").each(function (index) {
                    $(this).addClass("hovered-stars");
                    if (index == current.index()) {
                        return false;
                    }
                })
            })
            $(".li").mouseleave(function () {
                $(this).removeClass("hovered-stars");
            })
            $(".li").click(function () {
                $(".li").removeClass("clicked");
                $(".hovered-stars").addClass("clicked");
                number = $(".clicked").length;
                $("#message").html("You rated " + number + " Stars");
            })
            console.log(number);
        })
    

    【讨论】:

    • 是的,但它仍然没有在点击侦听器之外打印值。在控制台中打印 0。
    • 那你写的逻辑可能有问题。访问变量没有问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 2014-01-29
    • 1970-01-01
    • 2011-04-15
    • 2017-06-01
    • 2020-04-26
    相关资源
    最近更新 更多