Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/453.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用变量';这';在设定间隔内_Javascript_Jquery - Fatal编程技术网

Javascript 使用变量';这';在设定间隔内

Javascript 使用变量';这';在设定间隔内,javascript,jquery,Javascript,Jquery,嗨,我想在jquery函数的setInterval中使用'this'变量 我在“不工作”行之后编写“//此代码不工作” (function($) { $.fn.rotate=function () { var counter=0; var timer=setInterval(function () { count

嗨,我想在jquery函数的setInterval中使用'this'变量 我在“不工作”行之后编写“//此代码不工作”

 (function($)
            {
                $.fn.rotate=function () {
                    var counter=0;
                    var timer=setInterval(function () {
                        counter++;
                        var transform='rotate('+counter+'deg)';
                        $(this).css('transform',transform); // this code dont work
                        if(counter>=300)
                            clearInterval(timer);
                    },1);
                    return this;
                };
                $('#socialNetworks i').rotate();
            }(jQuery))

非常感谢在定义函数时使用箭头函数维护调用函数的上下文。因此,您将能够在函数中正确访问此

( $ => {
    $.fn.rotate=function () {
        var counter=0;
        var timer=setInterval(function () {
            counter++;
            var transform='rotate('+counter+'deg)';
            $(this).css('transform',transform); // this code dont work
            if(counter>=300)
                clearInterval(timer);
        },1);
        return this;
    };
    $('#socialNetworks i').rotate();
})(jQuery)

是的,但我不理解这个主题,请将答案与我的代码一起发送,我的母语不是英语,我不理解主题TL;DR是传递给
setInterval
的“回调”函数在
setInterval
上下文中用
this
调用。如果可能,您应该使用箭头函数(
=>
),或者使用将函数的
this
更改为语法定义的
this
。请尝试查找有关JavaScript的
如何在您的母语中工作的文档。建议如何解决问题的解释在哪里。绝对不是。只有代码的答案没有解释多少是无用的。看见