当按钮被点击超过X次时,如何添加Class



我学习了本教程;工作正常,但现在我尝试更改页面的背景颜色,当按钮被点击超过X次时(例如10次(。

我正试图用这样的IF添加类:

var i = 10;
if (i < data.length) {
document.getElementById('first').classList.add("achieved");
}
#first.achieved { background-color: green; }
<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>

但什么也没发生!你能帮我吗?

如果你想知道data.length从哪里来,它在这里

通知后端有点击的代码

// 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

更新:我解决了这个问题,我只是忘记链接我的CSS和HTML。。。我真的很笨

简短回答

你们可以用closures做这样的事情。

功能描述

在这种方法中,您必须创建一个负责保存计数的父函数和一个由其父函数返回的子父函数,以将计数的值增加1,然后检查它是否等于10。

const button = document.querySelector('#myButton');
function clickCount() {
const countElement = document.getElementById('count');
let count = 0
return function countPlusOne() {
count += 1;

countElement.textContent = count;
if (count === 10) {
document.getElementById('first').classList.add("achieved");
}
}
}
const countPlusOne = clickCount();
button.addEventListener("click", countPlusOne);
#first.achieved {
background-color: green;
}
<div id="first">
<h1>Node + Express + MongoDb example</h1>
<p id="counter">Loading button click data.</p>
<button id="myButton">Click me!</button>
</div>
<p>Button click count is currently at <span id="count">0</span></p>

最新更新