簡體   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