如何让我的脚本互相交互?

问题描述 投票:2回答:1

当我的网页加载后,它运行此脚本:

$(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()

我该如何实现这一目标?

javascript jquery
1个回答
0
投票

首先,我建议使用$.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;
}
© www.soinside.com 2019 - 2024. All rights reserved.