getElementById()打破循环

时间:2012-01-29 19:45:42

标签: javascript

我有问题......这是交易。我有很多元素和一个按钮来隐藏它们,看起来像

Category1(例如id =“1”)
- line1(例如,那个div,id =“1-1”class =“ blue ”)
- line2(例如,那个div,id =“1-2”class =“ blue ”)
- line3(例如,那个div,id =“1-3”class =“red”)
- line4(例如,那个div,id =“1-4”class =“green”)

等。行有不同的类,这是一个很长的故事。事情是,如果没有可见元素,我需要隐藏“Category1”标题(div)。那没关系。 但是,当我再次出现该类别的任何一行时,我需要显示它......

所以我有这个 (idl =线类(关联大量,包含蓝色,红色,绿色等),通过自定义函数getElementsByClassName()...这就是“show line”函数

   for (i=0;i<idl.length;i++) 
   {
   idl[i].style.display = "block";
   cla = idl[i].id; 
   if (cla[1]='-') {cla = cla[0];}
   else {cla = cla[0] + cla[1];}     //weird way to get Category id but works
                                     //just cut off "-1" "-2" part of line IDs
                                     // loop is doing it's job.

   /* if ( getElementById(cla) || getElementById(cla).style.display!="block" ) {
      getElementById(cla).style.display = "block";
      } 
   */

    // now here if I use 3 lines above it stops. 1st loop and that's it.
    // even after getElementById("12345"), after getElementById(everything here)
    // and nothing happening if i put alert anything after

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

全局范围内没有getElementByIdgetElementByIddocument上的方法,因此您尝试将未定义的值作为函数调用并失败。你想要更像这样的东西:

var el = document.getElementById(cla);
if(el && el.style.display != 'block')
    el.style.display = 'block';

另请注意,逻辑已修复为使用&&而不是||