【问题标题】:How to make a jQuery function accessible from anywhere?如何使 jQuery 函数可以从任何地方访问?
【发布时间】:2015-12-02 15:17:38
【问题描述】:

为了让一个普通的 JS 函数在任何地方都可以访问,我只需要在 jQuery(document).ready(function($){}) 之外声明它。但是如果这个 JS 函数包含 jQuery 的东西呢?那我怎样才能让它从任何地方访问,尤其是从不同的 JS 文件呢?

【问题讨论】:

  • 您在标题中加载 jQuery。这使得 jquery 可以在任何地方访问。将多个脚本加载到页面中就像注入代码。以正确的顺序在一个函数中定义一个函数,第二个脚本可以访问它。
  • 你必须想象所有的 javascript 都按照它们加载到页面中的顺序运行,所以如果包含 jQuery,之后的任何脚本都可能使用它(这并不一定意味着它应该或者它会从中受益)。

标签: jquery scope


【解决方案1】:

以完全相同的方式。只要您在函数之前包含jQuery

所以

<script src="jquery.js"></script>
<script src="yourglobalfunctionshere.js"></script>
<script src="documentreadystuff.js"></script>
<script>
jQuery(document).ready(function($){
    //or here some stuff
})
</script>

【讨论】:

  • 如果您将$ 注入其中,那不需要成为 IIFE 吗?
  • @SterlingArcher 不,这是文档就绪处理程序的简写,在就绪处理程序中明确传递 '$' 作为 jQuery 引用。 ready伪事件处理程序的第一个参数总是jQueryHowever, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code
猜你喜欢
  • 2015-08-18
  • 1970-01-01
  • 1970-01-01
  • 2014-04-01
  • 1970-01-01
  • 2021-08-13
  • 2017-03-20
  • 2022-08-19
  • 2016-03-10
相关资源
最近更新 更多