javascript - 无法在 'this' 函数内的函数内使用 'each' 定位 div

标签 javascript jquery html css this

因此,我只想让这些鼠标在您点击它们时经过一段随机时间后重新出现。我正在尝试使用每个函数来定位每个 .mouse div,这工作正常,但是如果我再次将“this”放入 settimeout 函数中,它们就不会返回。如果我将 1 个特定鼠标作为目标,如下例所示,1 会按预期返回。它显然没有将每个函数的“this”带入下一个函数。

下面的代码有 '.mouse-1' 但这是我想要 'this' 的地方

http://thetally.efinancialnews.com/tallyassets/wackamouse/index.html

<div class="container">
  <div class="mice">
    <div class="mouse mouse-1"></div>
    <div class="mouse mouse-2"></div>
    <div class="mouse mouse-3"></div>
    <div class="mouse mouse-4"></div>
    <div class="mouse mouse-5"></div>
    <div class="mouse mouse-6"></div>
    <div class="mouse mouse-7"></div>
    <div class="mouse mouse-8"></div>
    <div class="mouse mouse-9"></div>
  </div>
</div>

^ html 非常简单。将鼠标绝对定位在图像上。他们只需要躲起来然后在随机时间后回来

$('.mouse').each(function() {

$(this).click(function() {

$(this).animate({
'background-position-x': '0',
'background-position-y': '40px'
}, 300, function() {

var rand = Math.round(Math.random() * (7000 - 2000)) + 500; //between 7secs and 2.5 secs
setTimeout(function(){
    $('.mouse-1').animate({
 'background-position-x': '0',
 'background-position-y': '0'});
            },  rand);

    });

});

});

另外,在旁注中,我希望鼠标 div 在按下时无法点击

非常感谢

最佳答案

绑定(bind)它,这样你就可以在 setTimeout 的范围内拥有它:

 $('.mouse').each(function () {

    $(this).click(function () {

        $(this).animate({
            'background-position-x': '0',
                'background-position-y': '40px'
        }, 300, function () {

            var rand = Math.round(Math.random() * (7000 - 2000)) + 500;
            setTimeout(function () {
                $(this).animate({
                    'background-position-x': '0',
                        'background-position-y': '0'
                });
            }.bind(this), rand);

        }.bind(this));

    });

});

Demo

关于javascript - 无法在 'this' 函数内的函数内使用 'each' 定位 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26283619/

相关文章:

javascript - 将 ng-class 绑定(bind)到自定义 AngularJS 指令中的本地范围表达式

jquery - 使用 JQuery 从容器末尾删除项目

javascript - 如何将 jQuery 添加到 SoloLearn Playground 部分?

javascript - 用js加载本地.csv,用d3.js处理

jQuery - 函数后跟同一事件中的 if 条件

javascript - 导航时刷新 Vue 组件

javascript - JSON:在另一个 JSON 对象中重用 JSON 对象

javascript - Chrome 扩展 - 记住用户输入的 JavaScript

jQuery 切换标签内容

jquery - github.io 阻止了 ajax 请求