首页 > 解决方案 > 为什么我的代码没有按我预期的方式工作?

问题描述

我正在使用 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”的元素。

标签: javascripthtmlcss

解决方案


您快到了!item.classlist.add不是getter/setter,而是一种方法。所以为了给元素添加一个类,你需要像这样调用它: item.classList.add('your-class-here');


推荐阅读