【问题标题】:Function Variable passed to setTimeout not working?传递给 setTimeout 的函数变量不起作用?
【发布时间】:2010-10-12 18:55:47
【问题描述】:

谁能告诉我为什么这不起作用?

function changeBG(element_id){
        document.getElementById(element_id).className= "arrowActive";
        setTimeout("document.getElementById("+element_id+").className= 'arrow'", 300);
}

在 firebug 中我收到一条错误消息,指出传递给 setTimeout() 的 element_id 未定义。

【问题讨论】:

    标签: javascript iphone html


    【解决方案1】:

    试试:

    setTimeout("document.getElementById('" + element_id + "').className= 'arrow'", 300);
    

    请注意,我在您传递给getElementById 的字符串参数中添加了引号。

    【讨论】:

      【解决方案2】:

      变量element_id 将是一个字符串,因此您的超时代码将如下所示:

      document.getElementById(myId).className = ...
      

      注意 myId 应该用引号括起来,但不是。

      更好的方法是使用闭包,如下所示:

      function changeBG(element_id)
      {
              var elm = document.getElementById(element_id);
              elm.className = "arrowActive";
              setTimeout(function() { elm.className= 'arrow'; }, 300);
      }
      

      需要注意的是,在a字符串中传递代码是not recommended

      【讨论】:

        【解决方案3】:

        最好的方法是使用闭包

        function changeBG(element_id)
        {
                var elem = document.getElementById(element_id);
                elem.className= "arrowActive";
                setTimeout( function(e)
                {
                        return function()
                        {
                                e.className = 'arrow';
                        }
                }( elem ), 300);
        }
        

        【讨论】:

          猜你喜欢
          • 2018-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-16
          • 1970-01-01
          • 1970-01-01
          • 2018-08-29
          • 1970-01-01
          相关资源
          最近更新 更多