假设我有一个 JavaScript 函数,在页面加载后插入到页面中,然后我如何调用该函数。例如,让事情变得简单。假设我进行 Ajax 调用来获取脚本的标记,并返回以下内容:
<script type="text/javascript">
function do_something() {
alert("hello world");
}
</script>
如果我随后将此标记添加到 DOM,我可以稍后调用 do_something()
吗?
我使用 jQuery JavaScript 框架。
最佳答案
您可以使用 jQuery 的 $.getScript(...)
函数。大多数情况下,这可以满足页面加载后异步加载 JavaScript 的需要。
以下是相应的文档:http://api.jquery.com/jQuery.getScript/
基本上你可以做类似的事情
$.getScript("http://myhost.com/scripts/myscript.js", function(){
//at this point the script has been attached to the page and processed
//you can use it here
});
关于javascript - 是否可以在页面加载后添加 JavaScript 并执行它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7777365/