【问题标题】:How to have my scripts interact with each other?如何让我的脚本相互交互?
【发布时间】:2018-02-23 14:59:17
【问题描述】:

当我的网页加载完毕后,它会运行这个脚本:

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

我如何做到这一点?

【问题讨论】:

  • 首先我建议使用$.getScript 来加载你的JS 代码,假设你不能将它直接嵌入到&lt;script&gt; 标记中。要解决您的实际问题,您只需要以您需要的方式构建它。只需创建一个像var MyScript = {}; 这样的对象,然后将所有函数和变量作为属性放在该对象中
  • 感谢@RoryMcCrossan,但如果您能将以上内容放入答案中,我将非常感激。
  • 好的,我给你加了

标签: javascript jquery


【解决方案1】:

首先我建议使用$.getScript 来加载你的JS 代码,假设你不能将它直接嵌入到&lt;script&gt; 标记中。

要解决您的实际问题,您只需按照您需要的方式构建它。只需创建一个像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;
}

【讨论】:

  • 感谢@RoryMcCrossan,我正在尝试您的解决方案,我可以看到来自'/get_script' 的响应负载确实是脚本。但是console.log(MyScript.random_string); 行没有被触发,我在 int 中也没有其他内容。我也尝试从浏览器控制台调用MyScript.random_string;,但这会引发ReferenceError: MyScript is not defined。外部脚本不需要以某种方式附加到文档中吗?
猜你喜欢
  • 1970-01-01
  • 2021-04-14
  • 2013-09-04
  • 1970-01-01
  • 2014-12-24
  • 1970-01-01
  • 2011-10-24
  • 2015-03-11
  • 2023-03-04
相关资源
最近更新 更多