使用 setAttribute 方法设置属性
在本步骤中,你将学习如何更改元素的属性,例如链接的 href 或图片的 src。setAttribute() 方法用于此目的。它接受两个参数:要设置的属性名称,以及该属性要设置的值。
我们的 index.html 文件包含一个 ID 为 labex-link 的链接(<a> 标签)。让我们更改其 href 属性,使其指向 LabEx 网站。
将以下代码添加到你的 script.js 文件中。
// Select the link element
const link = document.getElementById("labex-link");
// Set its href attribute
link.setAttribute("href", "https://labex.io");
你完整的 script.js 文件现在应该如下所示:
const contentDiv = document.getElementById("main-content");
contentDiv.innerHTML = "The content has been changed by JavaScript!";
console.log(contentDiv);
// Select the link element
const link = document.getElementById("labex-link");
// Set its href attribute
link.setAttribute("href", "https://labex.io");
保存文件,切换到“Web 8080”选项卡并刷新。现在,如果你将鼠标悬停在“LabEx”链接上,你应该会在浏览器的状态栏中看到它指向 https://labex.io。点击它将尝试导航到该页面。