如何使用jQuery一次又一次地更改文本?

时间:2014-12-15 20:57:02

标签: javascript php jquery html css

我在stackoverflow HERE上找到了这个代码,但它对我不起作用......

我只能看到这个:

Hello world!
Here is a message: 

,但我没有看到时间之后应该改变的消息......

我从我的文件index.html中复制/粘贴整个代码:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">


</script>
</head>
<body>
<script type="text/javascript">
function nextMsg() {
    if (messages.length == 0) {
        alert("redirecting");
    } else {
        $('#message').html(messages.pop()).fadeIn(500).delay(1000).fadeOut(500,     nextMsg);
    }
};

var messages = [
    "Hello!",
    "This is a website!",
        "You are now going to be redirected.",
    "Are you ready?",
    "You're now being redirected..."
].reverse();

$('#message').hide();
nextMsg();
</script>

<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>
</html>

提前致谢:)

1 个答案:

答案 0 :(得分:3)

只需更改顺序,不要在代码的开头始终执行javascript和/或使用文档准备好确保在执行js之前加载dom

&#13;
&#13;
<h1>Hello world!</h1>
    <p>Here is a message: <span id="message"></span></p>

<script>
     $(document).ready(function() {
function nextMsg() {
    if (messages.length == 0) {
        alert("redirecting");
    } else {
        $('#message').html(messages.pop()).fadeIn(500).delay(1000).fadeOut(500,nextMsg);
    }
};


var messages = [
    "Hello!",
    "This is a website!",
        "You are now going to be redirected.",
    "Are you ready?",
    "You're now being redirected..."
].reverse();

$('#message').hide();
nextMsg();
});
</script>
&#13;
&#13;
&#13;