开发者

Hide/Show Table Columns with Javascript (fix for all browsers?)

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){
        el开发者_开发问答ement_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.


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.

function getElementsByClass(searchClass,node,tag) {
    var classElements = new Array();
    if ( node == null )
        node = document;
    if ( tag == null )
        tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
        if ( pattern.test(els[i].className) ) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

Then you would re-write your method as follows.

var hidden = 1;

function toggleTable(){
    var element_array = getElementsByClass('foo');
    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;
}
toggleTable();


And what about jQuery.toggle()?

$(".disabled").toggle();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜