0

在 Jquery 中使用了 Random Number Effect中的 post 之类的代码.. 和结果http://jsfiddle.net/ZDsMa/94/ ...

现在我在一个文件 php( index.php) 中编写完整的代码 html 和 jquery 并放在我的服务器上......

<html>
<title>Randomize Number</title>
<head>
<style type="text/css">
#output {
    margin: 20px;
    padding: 20px;
    background: gray;
    border-radius: 10px;
    font-size: 80px;
    width: 160px;
    color: red;
}
</style>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var output, started, duration, desired;
// Constants
duration = 5000;
desired = '50';

// Initial setup
output = $('#output');
started = new Date().getTime();

// Animate!
animationTimer = setInterval(function() {
    // If the value is what we want, stop animating
    // or if the duration has been exceeded, stop animating
    if (output.text().trim() === desired || new Date().getTime() - started > duration) {
        console.log('animating');
        // Generate a random string to use for the next animation step
        output.text('' + Math.floor(Math.random() * 990)

        );

    } else {
        console.log('animating');
        // Generate a random string to use for the next animation step
        output.text('' + Math.floor(Math.random() * 990)

        );
    }
}, 1000);

</script>
</head>
<body>
<div id="output">-</div>                    
</body>
</html>

动画随机数未显示(jscript 未运行,仅带有“-”字符/css 的框)

我的代码有什么问题?

4

3 回答 3

1

You just need to make sure your code gets executed after the page is rendered. Try wrapping it with:

...
<script>
$( function () {
    var output, started, duration, desired;
    // Constants
    duration = 5000;

    ...

    }, 1000);
});
</script>
...

You can find more info here jQuery.ready().

于 2013-03-22T05:01:04.973 回答
0

嗨使用这个javascript代码它工作

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var output, started, duration, desired;
// Constants
duration = 5000;
desired = '50';

// Initial setup
output = $('#output');
started = new Date().getTime();

// Animate!
animationTimer = setInterval(function() {
    // If the value is what we want, stop animating
    // or if the duration has been exceeded, stop animating
    if (output.text().trim() === desired || new Date().getTime() - started > duration) {
        console.log('animating');
        // Generate a random string to use for the next animation step
        output.text('' + Math.floor(Math.random() * 990)

        );

    } else {
        console.log('animating');
        // Generate a random string to use for the next animation step
        output.text('' + Math.floor(Math.random() * 990)

        );
    }
}, 1000);
})
于 2013-03-22T05:05:50.307 回答
0

您需要将与 DOM 交互的代码包装在$(document).ready()回调中:

$(document).ready(function() {
    ...
})
于 2013-03-22T04:30:25.573 回答