safari ReferenceError:无法找到变量

ada*_*dam 3 javascript safari referenceerror

我在自己的DIV中有以下内容

<script>
function newfunc()
{
alert("here");
}
</script>
<button type="button" onclick="newfunc()">Press me</button>
Run Code Online (Sandbox Code Playgroud)

在IE和FF上工作正常,但在Safari(至少Safari 4.0.5)上它说"ReferenceError无法找到变量" - 现在内容被动态加载到DIV中似乎Safari无法看到函数定义在这个DIV中 - 但是,如果我将该功能newfunc()放在主HTML页面上(即不在DIV中),那么按下按钮会调用该功能.

好像Safari没有看到已添加到DIV的Javascript函数.

任何帮助,将不胜感激.

亚当

ndt*_*viv 5

动态添加到页面的Javascript需要为eval-d才能正确初始化.

为了使其能够正确地用于函数定义,需要对它们进行稍微不同的格式化.例如:

<script>
newfunc = function()
{
alert("here");
}
</script>
<button type="button" onclick="newfunc()">Press me</button>
Run Code Online (Sandbox Code Playgroud)

将内容添加到DIV后,从DIV中提取所有标记元素并评估其内容.

例如,使用PrototypeJS(http://www.prototypejs.org/api/):

$(divid).innerHTML.evalScripts();
Run Code Online (Sandbox Code Playgroud)

其中divid是您刚填充内容的div的ID.