当我的网页加载后,它会运行这个脚本:
$(function() {
return $.ajax({
type: "get",
dataType: "json",
url: "/get_script",
success: function(data, status, xhr) {
return $("#myScript").html(data.myScript);
}
});
});该脚本从我的服务器( data.myScript对象)获取另一个脚本。添加到我的网页中的新脚本如下所示:
<script>
initScript = function() {
return window.random_string = Math.random().toString(36).substring(7);
};
$(window).bind("popstate", 'hashchange', function() {
return initScript();
});
window.random_string = null;
initScript();
</script>如果新脚本需要为网页上的其他脚本提供变量,我会将它们放入window.my_variable变量中,但我希望能够调用例如MyScript.random_string。
我还希望能够从其他脚本触发initScript函数。就像MyScript.initScript()一样
我该如何实现这一点?
发布于 2018-02-23 23:13:35
首先,我建议您使用$.getScript加载JS代码,假设您不能将其直接嵌入到<script>标记中。
要解决你的实际问题,你只需要按照你需要的方式来组织它。只需创建一个类似var MyScript = {};的对象,然后将所有函数和变量作为属性放入该对象中,如下所示:
$.getScript('/get_script', function() {
// put logic to run after the script has loaded here...
// note that you don't need your .html(data.myScript) any more
MyScript.initScript();
console.log(MyScript.random_string);
});
// in your external script:
var MyScript = {
initScript = function() {
this.random_string = Math.random().toString(36).substring(7);
},
random_string: null;
}
https://stackoverflow.com/questions/48950650
复制相似问题