【问题标题】:Can't change className within an onclick function JS无法在 onclick 函数 JS 中更改 className
【发布时间】:2020-08-29 21:07:33
【问题描述】:

执行本教程,但是当我在检查器调试器上运行时,content.className 始终保持 ="" 它仅在分配的 .onclick 函数的设置转换期间打开。所以这个功能的效果只是暂时的。

var button= document.getElementById("show-more");

button.onclick = () =>{
    //of the content has a class name of open then we open the box
    if(content.className== "open"){
        //if it's already opened then we shrink the box
        //revert to normal
        content.className= "";
        button.innerHTML= "Show More";
    }else{
        //else we expand the box
        //if it's closed we add open as it's class
        content.className= "open";
        button.innerHTML = "Show Less";

    }
}```

【问题讨论】:

  • 为什么不使用 StackOverflow 中的代码 sn-p 功能发布可运行的代码?

标签: javascript scope classname


【解决方案1】:

尝试content.classList.add("open"); 添加 和content.classList.remove("open"); 删除

【讨论】:

  • 那么我做错了什么?和范围有关系吗?
  • 我试过了,结果还是一样var content = document.getElementById("content"); var button= document.getElementById("show-more"); button.onclick = () =>{ if(content.className== "open"){ //if it's already opened then we shrink the box //revert to normal content.classList.remove("open"); button.innerHTML= "Show More"; }else{ button.innerHTML = "Show Less"; content.classList.add("open"); } }
猜你喜欢
  • 1970-01-01
  • 2023-01-02
  • 2020-11-30
  • 2020-10-06
  • 1970-01-01
  • 2013-04-15
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
相关资源
最近更新 更多