gpt4 book ai didi

javascript - 一段时间后使用jQuery更改文本?

转载 作者:行者123 更新时间:2023-12-03 17:09:49 26 4
gpt4 key购买 nike

该站点上已经有一些答案,但无法弄清楚我需要什么。
使用此处给出的被接受为好的答案:How can I change text after time using jQuery?
但是,我不想让它发出警报,而是让它重新加载到它的第一条消息(为了清楚起见,添加完整的代码:

function nextMsg() {
if (messages.length == 0) {
// once there is no more message, I don't know how to start the script over (loop it)
} 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();
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>
</html>

在另一个答案中,我也找到了类似的东西,但我无法添加淡入和淡出:

        var example = ['<a href="#"> link1</a>', '<a href="#"> link2</a>'];

textSequence(0);
function textSequence(i) {

if (example.length > i) {
setTimeout(function() {
document.getElementById("sequence").innerHTML = example[i];
textSequence(++i);
}, 5000); // milliseconds

} else if (example.length == i) { // Loop
textSequence(0);
}

}
<div id="sequence"></div>

这似乎是一个简单的答案,但是虽然我在一定程度上了解 html 和 css,但 jscript 仍然超出我的能力范围,所以一个清晰的答案会很棒。
感谢任何会回答的人。

最佳答案

使用 pop在第一个示例中,主动从您的 messages 中删除元素数组 - 所以你不能“重新开始脚本”,因为你基本上已经破坏了你的数据。
想想pop就像一次一个地从袋子里取出一件元素然后扔掉一样——显然,当袋子里没有元素时——你不能再开始尝试从袋子里取出元素——因为里面什么都没有了袋子。

function nextMsg(index) {
if (messages.length === index) {
nextMsg(0);
} else {
$('#message').html(messages[index])
.fadeIn(500)
.delay(1000)
.fadeOut(500, () => nextMsg(index + 1));
}
};

var messages = [
'<a href="#"> link1</a>',
'<a href="#"> link2</a>',
'<a href="#"> link3</a>',
'<a href="#"> link4</a>'
];

$('#message').hide();

nextMsg(0);
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>

如您所见,无需 copy或复制数据——也不需要 reverse消息。
只需使用消息索引来跟踪要显示的消息并循环索引。

关于javascript - 一段时间后使用jQuery更改文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65405885/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com