通过innerHTML插入Javascript函数时的ReferenceError

时间:2011-11-07 00:24:49

标签: php javascript smarty innerhtml

我在调用通过innerHTML属性插入<div>的Javascript函数时遇到问题。我已经搜索了SO中的类似线程,但我无法找到解决此问题的方法。

在简化版中,我的内容如下:

MainPage.php

// ... Basic Headers 
<div id = 'list'>
    {include file="list.tpl"}
</div>
// More stuff...
<script type="text/javascript">
    function callbackFunction(data) {
        $('list').innerHTML = data.updatedListHTML;
        updateCalculatedFields();
    }
    // Perform a Ajax POST Request with the callbackFunction()
</script>

List.tpl

{if $thereIsData}
    // Create a table, populate its content...
    <script type="text/javascript">
        function updateCalculatedFields() {
             // Change some of the values in the created table...
        }
    </script>
{/if}

使用上面的代码,我在试图调用callbackFunction(data)函数时在updateCalculatedFields()中得到一个ReferenceError。我仔细检查了innerHTML是否已正确更新; updateCalculatedFields()函数(以及整个脚本标记)已添加到div中。但是,Javascript似乎无法找到注入函数。

只需稍加改动,功能就可以了。如果要将list.tpl更改为:

List.tpl(第2版)

{if $thereIsData}
    // Create a table, populate its content...
{/if}
<script type="text/javascript">
    function updateCalculatedFields() {
         // Change some of the values in the created table...
    }
</script>

两种情况之间的不同之处在于,在第二种情况中,updateCalculatedFields()函数从一开始就加载了页面。在第一个中,稍后将使用innerHTML添加它。所以,我的结论是Javascript不会注册通过innerHTML添加的函数。我非常怀疑这是事实;如果有人可以就这个问题作出解释,那将会很棒。

1 个答案:

答案 0 :(得分:1)

使用innerHTML插入时不会评估JavaScript。您需要自己eval()或向页面添加新的外部脚本标记。