从动态加载的innerHTML上下文运行自定义javascript

从动态加载的innerHTML上下文运行自定义javascript,javascript,html,ajax,function,innerhtml,Javascript,Html,Ajax,Function,Innerhtml,我有一个HTML文档 然后我动态加载一些上下文到#test div function change() { ws = document.getElementById(id); str = '<script>function ttest(){window.alert("Yahoo!!!")}</script><select><option onclick="ttest();">1</option><option >2&

我有一个HTML文档


然后我动态加载一些上下文到#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();
函数更改()
{
ws=document.getElementById(id);
str='函数ttest(){window.alert(“Yahoo!!!”)}12';
ws.innerHTML=str;
}
window.onload=change();
加载页面时,会加载自定义脚本

<script>function ttest(){window.alert("Yahoo!!!")}</script>
函数ttest(){window.alert(“Yahoo!!!”)}
不起作用

当它的put static没有任何innerHTML时,它可以完美地工作。 当它不是自定义函数时,它也可以工作


使用innerHTML或/和AJAX+innerHTML动态加载自定义函数时,如何使其工作?

通过
createElement将脚本添加到
文档.head
。比如说:

var script = document.createElement("script");
script.innerHTML = "function ttest() { alert('Yahoo'); }";
document.head.appendChild(script)

你说“不行”是什么意思?你想做什么?我收到一条消息说函数更改不存在。但是为什么你要插入这样的javascript代码呢?实际上我的代码有点复杂)。这只是一个关于如何运行动态加载的定制javascript的问题和解决方案。我不害怕分享,但是有太多的文本…试着写str='function ttest(){window.alert(“Yahoo!!!”)};谢谢,它很有效。。。。!!!!但是有一个更正——document.getElementsByTagName('head'),而不是document.head。
var script = document.createElement("script");
script.innerHTML = "function ttest() { alert('Yahoo'); }";
document.head.appendChild(script)