Connect JS message loop in HTML header
P粉731861241
P粉731861241 2023-09-05 10:55:30
0
1
482
<p>I've been trying to make a message loop that changes every hour (only displays one at a time), I'm ok with HTML but not so good with JS. (The message should be placed in h3 tag)</p> <p>I tried to link my JS loop into an HTML text element but failed. </p> <p> <pre class="brush:js;toolbar:false;">h3 = document.createElement("h3"); var messages = "Message 1", "Message 2", "Message 3", "Message 4", "Message 5", "Message 6"; var counter = 0; function myLoop() { setTimeout(myLoop, 3, 600, 000); document.getElementById("Message") document.body.appendChild(h3); } myLoop();</pre> <pre class="brush:html;toolbar:false;"><h3> <h3 id="Message"></h3> </h3></pre> </p>
P粉731861241
P粉731861241

reply all(1)
P粉239089443
  1. Don’t wrap the title in the title
  2. Looks like you want an array of messages. I show below how to create such an array
  3. When the element already exists on the page, there is no need to use appendChild
  4. 3,600,000 is not a valid number of milliseconds. Use 3600000 or 60*60*1000

In my code, I use eventListener to wait for the html element on the page to be available before executing

Statement (counter )%len will start at 0 and loop at the length of the message array using the remainderoperator%. It avoids if (counter=> length) counter = 0;

=> is an arrow function, constructed as follows

const functionName (parameter) => { };

Functionally equivalent to (and a few other things)

function functionName(parameter) { };

If you need to execute it every hour, please change 2000 to 3600000

const messages = ["Message 1", "Message 2", "Message 3", "Message 4", "Message 5", "Message 6"];
const len = messages.length;
let counter = 0;

window.addEventListener("DOMContentLoaded", () => { // 当页面加载完成且h3可用时
  const h3 = document.getElementById("Message");
  const myLoop = () => h3.textContent = messages[(counter++) % len]; // 循环并包装
  myLoop(); // 立即执行一次
  setInterval(myLoop, 2000); // 然后每2秒执行一次
});
<div>
  <h3 id="Message"></h3>
</div>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!