我在调用通过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}
使用上面的代码,我在试图调用updateCalculatedFields()
函数时在callbackFunction(data)
中得到一个ReferenceError。我已经仔细检查了,看到innerHTML已正确更新;,updateCalculatedFields()
函数(和整个脚本标签)已添加到div。然而,Javascript似乎无法找到注入的函数。
只要稍加改动,功能就可以工作了。如果列表。TPL将更改为:
列表。tpl (version 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添加的函数。不过,我非常怀疑这种情况;因此,如果有人能就这个问题给出一个解释就太好了。
当插入innerHTML时,不计算JavaScript。您要么需要自己eval()它,要么追加一个新的外部脚本标签到页面。