在 another.js 中调用 .js 函数

Call .js function in another.js

我有...

<html>
 <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="xpath.js"></script>
  <script src="myscript.js"></script>
  </head>
  <body>
     <!-- some html code -->
  </body>
</html>

myscript.js

$( document ).ready(function() {
   $("body").click(function(event){
       console.log(event.target);
       //call xpath.js (getxpath(event.target))
   });
});

xpath.js

here 本地存储

我该如何实现..?

从另一个文件访问函数

文件之间的代码分隔无关紧要(您可以毫无问题地将它们全部打包到一个文件中)。执行顺序和范围。网页上加载的所有脚本共享相同的全局范围,即 window,并且可以向其添加变量。

大多数库都这样做,以便您可以访问它们(例如,jQuery 创建一个全局 $ 变量,您可以在任何地方使用它)。

但是,您的 Xpath 脚本不会,因为它并不打算直接嵌入到网页中。它是 Firefox 插件的一部分。所以为了让它可以访问,你需要修改它。

正在修改xpath.js

一开始,改成这样:

define([
    "firebug/lib/string"
],
function(Str) {

...为此:

window.Xpath = new (function(Str) {

最后,更改为:

});

...为此:

})();

使用它

既然你这样做了,你就有了一个全局的 Xpath 对象,你可以像这样访问它:

$(function() {
   $("body").click(function(event){
       console.log(Xpath.getElementXPath(event.target));
   });
});