繁体   English   中英

从另一个js文件中的变量调用函数

[英]Call function from variable in another js file

我有这个代码

//first.js 
var site = {};

//and functions are declared like that
site.functionNames = function(){
    //some codes
};

//second.js
$("#element").click(function(){
    //more codes
   site.function;
   site.function();
   console.log(site);
});

如何从second.js click事件访问/调用first.js函数? 尝试了上面的那些,但是所有人都说站点是不确定的。 不知道是否是正确的方法。

:编辑:

文件已经按顺序声明,second.js紧随其后。

<script src="first.js" type="text/javascript"></script>
<script src="second.js" type="text/javascript"></script> 

只要声明javascript文件,您就可以使用它。

<head>
....
    <script src="first.js" type="text/javascript"></script> 
    <script src="second.js" type="text/javascript"></script> 
....
<head>

如果您倒转订单,将无法正常工作

    <script src="second.js" type="text/javascript"></script> 
    <script src="first.js" type="text/javascript"></script> 

除非在同一文件中定义了该函数,或者在尝试调用该函数之前已加载了一个函数,否则无法调用该函数。

除非函数的范围与尝试调用该函数的范围相同或更大,否则不能调用该函数。

在first.js中声明函数fn1,然后在第二秒中就可以拥有fn1();。

1.js:

function fn1 (){
    alert();
}

2.js:

fn1();

index.html:

<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>

来源: 在另一个js文件中调用javascript函数

浏览器将按照script标签的写入顺序读取它们,除非asynctrue 因此只需按照您想要的方式放置脚本标签,浏览器就会执行第一个之后的第二个。


编辑:
加载js文件可能存在错误。 签入浏览器开发工具。

这是一个有效的例子

Test.html

<!DOCTYPE html>
<html class="html" lang="es-ES">
<head>
    <script src="scripts/jquery-1.8.3.min.js" type="text/javascript"></script> 
    <script src="tfirst.js" type="text/javascript"></script>
    <script src="tsecond.js" type="text/javascript"></script> 
</head>
    <body>
        <div class="fieldwrapper" name="field1" id="field1" />
            First name: <input type="button" name="first" onclick="site.functionNames('html')"><br>
            Last name: <input type="button" name="second" id="other"><br>       
        </div>  
    <body>
</html>

tfirst.js

var site = {};

//and functions are declared like that
site.functionNames = function(v){
    alert("hello " + v);
};

tsecond.js

$(document).ready(function(){
    $("#field1").on('click', '#other', function () {            
        site.functionNames('second.js');   
        console.log(site);
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM