1

所以这段代码有效:

<script>
function animate() {
    var x = 0;
    var goUp = document.getElementById('rotationUp');
    var comeDown = document.getElementById('rotationDown');

    goUp.onmouseover = alert(x);
}
</script>

这不会:

<script>
function animate() {
    var x = 0;
    var goUp = document.getElementById('rotationUp');
    var comeDown = document.getElementById('rotationDown');

    goUp.onmouseover = function() {
    alert(x);
    }
}
</script>

唯一的区别是功能,我哪里出错了?

PS:我需要它作为一个函数工作

4

2 回答 2

-1

尝试

function animate() {
    var x = 0;
    var goUp = document.getElementById('rotationUp');
    var comeDown = document.getElementById('rotationDown');

    goUp.onmouseover = function() {
        alert(x);
    }
}
于 2013-08-28T13:29:38.063 回答
-1

尝试将您的 x 变量全局放置:

<script>
var x = 0;

function animate() {
    var goUp = document.getElementById('rotationUp');
    var comeDown = document.getElementById('rotationDown');

    goUp.onmouseover = function() {
        alert(x);
    }
}
</script>

如果它不起作用,请尝试window.x

        alert(window.x);

或者this.x

        alert(this.x);
于 2013-08-28T13:36:34.093 回答