运行 来自动态加载的 innerHTML 上下文的自定义 javascript
Run custom javascript from dynamicaly loaded innerHTML context
我有一个 HTML 文档
...
<div id="test"></div>
...
然后我将一些上下文动态加载到#test div。
function change()
{
ws = document.getElementById(id);
str = '<script>function ttest(){window.alert("Yahoo!!!")}</script><select><option onclick="ttest();">1</option><option >2</option></select>';
ws.innerHTML = str;
}
window.onload = change();
加载页面时自定义脚本
<script>function ttest(){window.alert("Yahoo!!!")}</script>
不起作用。
当它在没有任何内部HTML 的情况下放置静态时,它工作得很好。
当它不是自定义函数时它也可以工作。
当使用 innerHTML or/and AJAX+innerHTML 动态加载时,如何使我的自定义函数工作?
通过 createElement
将您的脚本添加到 document.head
。所以像这样:
var script = document.createElement("script");
script.innerHTML = "function ttest() { alert('Yahoo'); }";
document.head.appendChild(script)
我有一个 HTML 文档
...
<div id="test"></div>
...
然后我将一些上下文动态加载到#test div。
function change()
{
ws = document.getElementById(id);
str = '<script>function ttest(){window.alert("Yahoo!!!")}</script><select><option onclick="ttest();">1</option><option >2</option></select>';
ws.innerHTML = str;
}
window.onload = change();
加载页面时自定义脚本
<script>function ttest(){window.alert("Yahoo!!!")}</script>
不起作用。
当它在没有任何内部HTML 的情况下放置静态时,它工作得很好。 当它不是自定义函数时它也可以工作。
当使用 innerHTML or/and AJAX+innerHTML 动态加载时,如何使我的自定义函数工作?
通过 createElement
将您的脚本添加到 document.head
。所以像这样:
var script = document.createElement("script");
script.innerHTML = "function ttest() { alert('Yahoo'); }";
document.head.appendChild(script)