javascript - 为什么start = parseInt(spans[this.index].style.top);是undefined?

查看:82
本文介绍了javascript - 为什么start = parseInt(spans[this.index].style.top);是undefined?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<div class="bottom clearfix" id="bottom">
                <div class="one" id="div1">
                    <img src="../images/smallpic.png">
                    <span class="span" id="sp1">
                        <strong class="s1">家装监理</strong>
                        <em class="s2">4大验收阶段 78项验收标准全程把关</em>
                    </span>
                </div>
                <div class="two" id="div2">
                    <img src="../images/smallpic.png">
                    <span class="span" id="sp2">
                        <strong class="s1">家装监理</strong>
                        <em class="s2">4大验收阶段 78项验收标准全程把关</em>
                    </span>
                </div>
<div>


var bottom = document.getElementById("bottom");
var divs = bottom.getElementsByTagName("div");
var spans = bottom.getElementsByTagName("span");
var speed =-10;
var start =260;
var timer ;
var timerout;
for (var i = 0; i < divs.length; i++) {
        divs.index = i;
        divs[i].onmouseout = function(){
            timerout = setInterval(function(){
                start = parseInt(spans[this.index].style.top);
                console.log(start);
                start -=speed;
                spans[this.index].style.top = start+"px";
            },100);
        }
    };

解决方案

this是动态绑定的...

不想动态绑定可以考虑用箭头函数

for (var i = 0; i < divs.length; i++) {
    divs[i].index = i;
    // divs[i].onmouseout = function () {
    //     timerout = setInterval(function () {
    //         start = parseInt(spans[this.index].style.top);
    //         console.log(start);
    //         start -= speed;
    //         spans[this.index].style.top = start + "px";
    //     }, 100);
    // }
    divs[i].onmouseout = function () {
        timerout = setInterval(() => {
            start = parseInt(spans[this.index].style.top);
            console.log(start);
            start -= speed;
            spans[this.index].style.top = start + "px";
        }, 100);
    }
}

转码之后类似这样

divs[i].onmouseout = function () {
    var _this = this;

    timerout = setInterval(function () {
        start = parseInt(spans[_this.index].style.top);
        console.log(start);
        start -= speed;
        spans[_this.index].style.top = start + "px";
    }, 100);
};

这篇关于javascript - 为什么start = parseInt(spans[this.index].style.top);是undefined?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆