开发者

Is there a better way to write these functions?

I'm not a javascript programmer by any means, but this has been annoying me for the longest while,

is there a better way to write these two seperate functions. As in a single function?

function showAll()
{
   var collection = getElementsByClassName("dealHolder");
   for (var x = 0; x < collection.length; x++) 
   {
      setParentTrue(col开发者_开发百科lection[x].parentNode);                    
   }
}

function setParentTrue(obj) {
     if (obj.id != "deal") 
     {
          obj.id = "true";
          setParentTrue(obj.parentNode);
     }
     else
     {
        obj.style.display = 'block';
     }
}

Can I declare a function within another and recursively call it? any time I need to recurse I always seem to be creating a separate function specifically for it

Cheers for the advice


function showAll()
{
   var collection = getElementsByClassName("dealHolder"),
       x = 0,
       setParentTrue = function(obj) {
        if (obj.id != "deal") 
        {
            obj.id = "true";
            setParentTrue(obj.parentNode);
        }
        else
        {
            obj.style.display = 'block';
        }
   };
   for (x = 0; x < collection.length; x++) 
   {
      setParentTrue(collection[x].parentNode);                    
   }
}


Yes, you can declare a function within a function, as functions are objects.

function showAll()
{

    var setParentTrue = function (obj) {
         if (obj.id != "deal") 
         {
              obj.id = "true";
              setParentTrue(obj.parentNode);
         }
         else
         {
            obj.style.display = 'block';
         }
    }

   var collection = getElementsByClassName("dealHolder");
   for (var x = 0; x < collection.length; x++) 
   {
      setParentTrue(collection[x].parentNode);                    
   }
}


Actually - writing a separate function to hold what occurs within a loop is good practise so I would not change what you have above.

Actually - no I take that back - in this case the function within the loop is unlikely to be usable to anyone else, so I'd go for one of the examples below. Nested within the same object, but still separate function.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜