You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按钮点击超X次添加class无效的问题排查与解决

问题:按钮点击超过指定次数后无法触发页面背景色变化

我按照一份Node+Express+MongoDB教程开发的项目原本运行正常,现在想要实现按钮被点击超过10次时改变页面背景色的功能,尝试用以下逻辑添加CSS类,但没有任何效果:

前端尝试的代码

JavaScript逻辑

var i = 10;

if (i < data.length) {
  document.getElementById('first').classList.add("achieved");
}

CSS样式

#first.achieved { background-color: green; }

HTML结构

<html>
  <head>
    <meta charset="utf-8">
    <title>Node + Express + MongoDb example</title>
  </head>
  <body>
  <div id="first">
    <h1>Node + Express + MongoDb example</h1>
    <p id="counter">Loading button click data.</p>
    <button id="myButton">Click me!</button>
    </div>
  </body>
  <script src="client.js"></script>
</html>

后端处理点击事件的代码

// Replace the URL below with the URL for your database
const url =  'URLDATABASE';

MongoClient.connect(url, (err, database) => {
  if(err) {
    return console.log(err);
  }
  db = database;
  // start the express web server listening on 8080
  app.listen(8080, () => {
    console.log('listening on 8080');
  });
});

// serve the homepage
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

// add a document to the DB collection recording the click event
app.post('/clicked', (req, res) => {
  const click = {clickTime: new Date()};
  console.log(click);
  console.log(db);

  db.collection('clicks').save(click, (err, result) => {
    if (err) {
      return console.log(err);
    }
    console.log('click added to db');
    res.sendStatus(201);
  });
});

// get the click data from the database
app.get('/clicks', (req, res) => {
  db.collection('clicks').find().toArray((err, result) => {
    if (err) return console.log(err);
    res.send(result);
  });
});

// change backgorund-color

更新:问题已解决

我发现问题所在了——只是忘记在HTML的<head>标签里引入CSS文件,导致写的样式根本没有生效,真是粗心!

内容的提问来源于stack exchange,提问作者Laurent Singamalom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 08:05:26