如何用classList.replace替换类名中的数字1?求正确实现方案
问题:移除类名中的数字1并替换类名
需求:把所有包含数字1的类名(比如my1bla、mu1bla)替换为去掉1后的版本(mybla、mubla),要用classList.replace实现,但现有代码无法正常工作。
用户代码:
<!DOCTYPE html> <html> <style> .my1bla { background-color: black; } .mybla { background-color: blue; } </style> <p>点击按钮改变DIV的样式类,背景色应该从黑色变成蓝色(期望效果)</p> <button onclick="myFunction()">试试</button> <div id="myDIV" class="my1bla"> I am a DIV element </div> <script> function myFunction() { var x = document.getElementById("myDIV"); if (x.classList.contains("1")) { x.classList.replace("1", ""); } else if (x.classList.contains("1")) { x.classList.replace("1", ""); } } </script>
问题分析
这段代码的核心问题:
classList.contains("1")是检查元素是否有单独的类名"1",而非类名中包含字符"1",所以替换逻辑永远不会触发。classList.replace(oldClass, newClass)需要传入完整的旧类名和新类名,不是单个字符的替换,直接传"1"和""完全不生效。
解决方法
遍历元素的所有类名,逐个检查是否包含"1",如果包含就生成去掉"1"的新类名,再用classList.replace完成替换:
<!DOCTYPE html> <html> <style> .my1bla { background-color: black; } .mybla { background-color: blue; } .mu1bla { color: white; } .mubla { color: yellow; } </style> <p>点击按钮改变DIV的类,背景色会从黑变蓝,文字颜色也会变化</p> <button onclick="myFunction()">试试</button> <div id="myDIV" class="my1bla mu1bla"> I am a DIV element </div> <script> function myFunction() { const x = document.getElementById("myDIV"); // 遍历元素的所有类名 for (const className of x.classList) { // 检查当前类名是否包含"1" if (className.includes("1")) { // 生成移除"1"后的新类名 const newClassName = className.replace("1", ""); // 替换旧类为新类 x.classList.replace(className, newClassName); } } } </script>
这样不管元素有多少个包含"1"的类名,都会被批量替换成去掉"1"的版本。
内容的提问来源于stack exchange,提问作者SL5net
相关产品推荐
相关产品推荐

