先贴上js代码
function judgeAll(){
var cancel = document.getElementById("cancel");
var judge = document.getElementsByClassName("judge");
cancel.onclick = function(){
if (judge.style.display=="") {
judge.style.display = "block";
cancel.value = "取消";
}else{
judge.style.display = "";
cancel.value = "编辑";
}
}
}
先获取按钮的id名和下拉框的class名,然后进行判定,如果下拉框judge被隐藏了,就display:block;如果下拉框judge没被隐藏,就display:none。很简单的想法,但是出错了。
![错误信息](https://i-blog.csdnimg.cn/blog_migrate/7106d3530c3139a9ad8cb1fdc49bb784.jpeg)
"Cannot set property 'display' of undefined"
开始还以为我语法写错了,检查后发现没有,然后上网查了原因,才发现原因在class名judge这里。
"judge.style.display=='none';"
class类不能简单直接拿来判断,因为具有多个class,所以要加上数组才能判断。
改进代码如下:
function judgeAll(){
var cancel = document.getElementById("cancel");
var judge = document.getElementsByClassName("judge");
cancel.onclick = function(){
if (judge[0].style.display == '' ) {
for(var i=0;i<judge.length;i++){
judge[i].style.display = "block";
cancel.value = "取消";
}
}else if(judge[0].style.display == 'block'){
for(var i=0;i<judge.length;i++){
judge[i].style.display = "";
cancel.value = "编辑";
}
}
}
}