setTimeout使用问题

ton*_*nyf 0 javascript

我有以下javascript但我在使用setTimeout时遇到问题,即:

function setUrl()
{
  // Get system URL details
  var url_path = new String(window.location.pathname);

  var new_url;

  new_url = window.location.host;
  }
  setTimeout("setValue('ONE_UP_URL',new_url);",2000);
}
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,我收到错误:'new_url'未定义.

非常感谢您使用setTimeout调用此javascript函数的帮助.

谢谢.

CMS*_*CMS 7

不要使用字符串作为setTimeout函数调用的第一个参数,使用匿名函数.

你还有一个额外的大括号:

function setUrl() {
  // Get system URL details
  var url_path = window.location.pathname,
      new_url = window.location.host;

  setTimeout(function () {
    setValue('ONE_UP_URL',new_url);
  }, 2000);
}
Run Code Online (Sandbox Code Playgroud)

如果您使用字符串,它将被评估,并不是真的建议.

通过使用评估代码eval(及其亲戚Function,setTimeoutsetInterval)被认为是危险的,因为他们将执行你通过与呼叫者的特权码,并且几乎所有的时间有一个解决办法,以避免它们.

其他小事:

  • 在代码中调用String构造函数是多余的,因为window.location.pathname它已经是一个字符串.
  • 您可以在单个var语句中声明函数变量.


Joh*_*her 6

你有一个流氓闭合支架.要么缺少更多代码,要么只需删除它.(setTimeout上面的行.)

另外,你应该替换这个:

setTimeout("setValue('ONE_UP_URL',new_url);",2000);
Run Code Online (Sandbox Code Playgroud)

有了这个:

setTimeout(function() { setValue('ONE_UP_URL', new_url); }, 2000);
Run Code Online (Sandbox Code Playgroud)