使用 Javascript 隐藏/显示表列(修复所有浏览器?)
我有一个长表,有很多列,对于用户来说它看起来真的很难看。我想做的是创建一个简单的按钮,充当开关,打开和关闭某些列。
有些列是不需要的,所以我所做的就是为每个不需要的列添加一个类,例如: ....
现在,我认为我可以做的是:
var hidden = 1;
function toggleTable(){
element_array = document.getElementsByClassName('disabled');
for(i = 0; i < element_array.length; i++){
if(hidden == 1){
element_array[i].style.display = 'none';
}else{
element_array[i].style.display = '';
}
}
if(hidden == 1) hidden = 0;
else hidden = 1;
}
这在 Firefox 中大部分有效,但在 IE(7+8) 中进行一些快速测试,我得到以下结果: 消息:对象不支持此属性或方法
显然表明 IE 不想让我简单地更改“display:none;”对于诸如表列/行之类的内容。
我想不出任何解决方法。理想情况下,我想要一个完全交叉兼容的解决方案来切换某些表列的显示,但如果它在旧版浏览器(例如:IE6)中不兼容,那么也可以。
I have a long table with many many columns and it looks really ugly for the users. What I wanted to do was create a simple button that would act as a switch, to turn on and off some of the columns.
Some of the columns are not needed, so what I did was add a class to every that wasn't needed, eg: ....
Now, what I thought I could do was this:
var hidden = 1;
function toggleTable(){
element_array = document.getElementsByClassName('disabled');
for(i = 0; i < element_array.length; i++){
if(hidden == 1){
element_array[i].style.display = 'none';
}else{
element_array[i].style.display = '';
}
}
if(hidden == 1) hidden = 0;
else hidden = 1;
}
This works for the most part in Firefox, but some quick tests in IE(7+8) and I get the following:
Message: Object doesn't support this property or method
Obviously indicating that IE doesn't want to let me simply change "display: none;" for something like table columns/rows.
I can't think of any workarounds. Ideally I'd like a fully cross-compatible solution to toggling the display of certain table columns,but if it's not compatible in the older browsers (eg: IE6) then that would also be OK.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您收到的错误不是因为 IE 不想设置显示属性,而是因为 IE 中未实现 getElementsByClassName 方法。如果您想要该方法的实现,您可以使用达斯汀·迪亚兹 (Dustin Diaz) 编写的这个方法。
然后您将按如下方式重写您的方法。
The error that you're getting is not because IE doesn't want to set the display property, it's because the getElementsByClassName method isn't implemented in IE. If you want an implementation of that methods you can use this one which was written by Dustin Diaz.
Then you would re-write your method as follows.
那么 jQuery.toggle() 又如何呢?
And what about jQuery.toggle()?