javascript - 为什么我的代码没有按我预期的方式工作?
问题描述
我正在使用 Javascript 来更改 HTML 元素。我更改了 innerText 并且我正在尝试更改课程。innerText 发生了变化……但“美丽”类不适用于 ID 为“top”的元素。为什么不 ?
我检查了是否调用了该函数。显然是......因为 innerText 已更改。
function beautify(){
item = document.getElementById("top");
item.classList.add = "beautiful";
item.innerText = "Why does it not work ?";
return;
}
.beautiful{
color: blue;
font-weight: bold;
font-family: helvetica;
}
<h1 id="top">I'm going to change</h1>
<button onclick="beautify()" >Click here for a special effect</button>
我期待按钮不仅可以更改 innerText,还可以添加样式,将类“beautiful”添加到 id 为“top”的元素。
解决方案
您快到了!item.classlist.add
不是getter/setter,而是一种方法。所以为了给元素添加一个类,你需要像这样调用它:
item.classList.add('your-class-here');
推荐阅读
- c - 打印随机数而不是我的 var
- assembly - System V amd64 如何处理很长的返回值?
- javascript - LeafletJs - 无法设置未定义的属性“L”
- java - 我应该把connection.close()放在java中吗?
- android - 如何从文件添加房间迁移
- regex - 如何使用apache删除请求url中的最后一个字符?
- c# - 是否可以在 .NET Core Web 应用程序的任务管理器中设置显示名称?
- css - 如何正确设置变换原点以创建完美的 X 符号?
- javascript - 内联事件不起作用(React+Express)
- c - Ncurses 库和从文件中读取