英文:
I'm getting an error while trying to create a dynamic title
问题
<title id="title">我的网站</title>
var titles = ["我的网站", "很高兴见到你!😁", "祝你有美好的一天!🌞"];
var index = 0;
function changeTitle() {
document.getElementById("title").innerText = titles[index];
index = (index + 1) % titles.length;
}
setInterval(changeTitle, 7000);
英文:
I want to create a dynamic title for my website using HTML and JavaScript. However, I'm getting an error in the developer console that says 'TypeError: null is not an object (evaluating 'document.getElementById("send").addEventListener')'. I want to understand why it's not reading the objects in the JavaScript-defined array.
JS:
var titles = ["My website", "Glad to see you!😍", "Have a nice day!🥳"];
var index = 0;
function changeTitle() {
document.getElementById("title").innerText = titles[index];
index = (index + 1) % titles.length;
}
setInterval(changeTitle, 7000);
HTML :
<title id="title">My website</title>
答案1
得分: 2
你不应该在<body>
标签内声明<title>
。它是为文档的<head>
部分保留的。它指定了网页的实际标签/窗口标题。
<!-- 开始代码片段: js 隐藏: false 控制台: true Babel: false -->
<!-- 语言: lang-js -->
const customTitleEl = document.getElementById("title");
const titles = ["我的网站", "很高兴见到你!😊", "祝你有美好的一天!🌞"];
let currentIndex = 0;
function changeTitle() {
customTitleEl.textContent = titles[currentIndex];
currentIndex = (currentIndex + 1) % titles.length;
}
changeTitle(); // 初始调用
setInterval(changeTitle, 1000); // 每“秒”更新
<!-- 语言: lang-html -->
<!-- <title> 应该在文档的 <head> 部分中声明(只有一次!) -->
<!-- 在 <body> 中使用一个 <div> 替代 -->
<div id="title">我的网站</div>
<!-- 结束代码片段 -->
如果你实际上想要更新网页的标题,可以调用:
document.title = '我的新标题';
英文:
You should not declare a <title>
inside the <body>
. It is reserved for the document's <head>
. It specifies the actual tab/window title for the webpage.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const customTitleEl = document.getElementById("title");
const titles = ["My website", "Glad to see you!😍", "Have a nice day!🥳"];
let currentIndex = 0;
function changeTitle() {
customTitleEl.textContent = titles[currentIndex];
currentIndex = (currentIndex + 1) % titles.length;
}
changeTitle(); // Call it initially
setInterval(changeTitle, 1000); // Update every "second"
<!-- language: lang-html -->
<!-- The <title> should be declared in the document <head> (only once!) -->
<!-- Use a <div> inside the <body> instead -->
<div id="title">My website</div>
<!-- end snippet -->
If you actually want to update the webpage's title, call:
document.title = 'My new title';
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论