如何获取JavaScript动态创建元素的ID并实现点击切换背景色功能
实现动态按钮的点击切换与ID获取
嘿,这个需求很好实现,咱们有两种实用的方式来解决这个问题,我给你一步步讲清楚:
方法一:创建按钮时直接绑定点击事件
这种方式逻辑直观,在每一个动态按钮被创建出来的时候,直接给它绑定点击处理函数,适合按钮数量不多的场景。
修改后的完整代码:
<body> <button id="crBtn" onclick="crBtn()">CLICK TO CREATE BUTTONS</button><br> <style> .name { background-color: aquamarine; border: none; width:300px; height: 50px; cursor: pointer; margin-right: 10px; margin-bottom:10px; } #crBtn { width:500px ; height:60px; background-color: blue; border: none; margin:30px; color:white; font-size: 30px; } .name:hover { background-color: skyblue; color:aliceblue; } /* 新增切换后的样式类 */ .name.active { background-color: coral; color: #ffffff; } </style> <script> var idNum = 0; function crBtn() { idNum++; var button = document.createElement("button"); button.innerHTML="HERE"; button.setAttribute("class","name"); button.setAttribute("id","na"+idNum); // 给动态按钮绑定点击事件 button.addEventListener('click', function() { // 切换背景色:通过toggle切换active类 this.classList.toggle('active'); // 获取并打印当前按钮的ID console.log('点击的按钮ID:', this.id); }); document.body.appendChild(button); } </script> </body>
代码说明:
- 新增了
.name.activeCSS类,用来定义按钮切换后的背景色样式 - 在创建按钮的
crBtn函数里,通过addEventListener给每个动态按钮绑定点击事件 - 点击时用
this.classList.toggle('active')切换样式类,同时通过this.id获取当前按钮的ID并打印
方法二:使用事件委托(更高效)
如果需要创建大量动态按钮,事件委托会是更优的选择——利用事件冒泡机制,只给父元素(比如body)绑定一次事件,就能处理所有动态按钮的点击,不用给每个按钮单独绑定事件。
修改后的完整代码:
<body> <button id="crBtn" onclick="crBtn()">CLICK TO CREATE BUTTONS</button><br> <style> .name { background-color: aquamarine; border: none; width:300px; height: 50px; cursor: pointer; margin-right: 10px; margin-bottom:10px; } #crBtn { width:500px ; height:60px; background-color: blue; border: none; margin:30px; color:white; font-size: 30px; } .name:hover { background-color: skyblue; color:aliceblue; } .name.active { background-color: coral; color: #ffffff; } </style> <script> var idNum = 0; function crBtn() { idNum++; var button = document.createElement("button"); button.innerHTML="HERE"; button.setAttribute("class","name"); button.setAttribute("id","na"+idNum); document.body.appendChild(button); } // 事件委托:给body绑定点击事件 document.body.addEventListener('click', function(e) { // 判断点击的元素是否是我们的动态按钮(排除创建按钮本身) if(e.target.classList.contains('name') && e.target.id !== 'crBtn') { e.target.classList.toggle('active'); console.log('点击的按钮ID:', e.target.id); } }); </script> </body>
代码说明:
- 不需要在创建按钮时绑定事件,只在页面加载完成后给
body绑定一次点击事件 - 通过事件对象
e.target获取点击的元素,判断它是否带有.name类且不是创建按钮本身 - 同样用
classList.toggle切换样式,通过e.target.id获取按钮ID
两种方法都能满足你的需求,你可以根据实际场景选择~
内容的提问来源于stack exchange,提问作者Aseel.kkh
相关产品推荐
相关产品推荐

