2014-01-19 106 views
1

我正在藉助外部js文件與MVC4應用程序一起工作。在視圖(.cshtml)文件中,我有一個函數,它根據按鈕單擊執行在網格中創建行的操作, 。 我已經定義了外部.js文件中的按鈕單擊。 但是,當我試圖從該外部js文件方法調用內部腳本函數時,它會拋出一個異常,表示該特定方法未定義。如何從外部js文件方法調用內部腳本函數?

我上網,但沒能找到令人信服的答案..

是什麼,我想可能嗎?......我應該如何實現呢?

任何的js專家在那裏可以幫助我解決這個...

感謝所有...;)

編輯:

這是外部.js文件:

$('#AddRowButton').on('click', function() { 
    window.CreateRow(); 
    } 

在我看來:(CSHTML)

<script> 
    function CreateRow() 
    { 
    // creting row goes here... 
    } 

    window.CreateRow = CreateRow; //defined like what @joseeight suggested... 
    </script> 
+0

「內部」函數是全局函數嗎?它在被調用之前被定義了嗎?你能在這裏展示你的代碼的精簡版嗎? – nnnnnn

+0

你能否提供如何在你的視圖中包含'external.js'? – Grundy

回答

1

這很可能是由於範圍問題。內部腳本和外部必須位於不同的範圍內。解決這個問題的最簡單和最簡單的方法是將內部方法添加到Window,並在外部訪問它。

//Internal script 
function myInternalMethod() { 
    //some code.. 
} 
window.myInternalMethod = myInternalMethod; 

因爲窗口是全球性的,名字是一樣的,你既可以在外部腳本引用時使用window.myInternalMethod或myInternalMethod。

+0

對不起,仍然沒有運氣...;( – user2771399

+1

你能發表一些代碼嗎?很難看到發生了什麼:) – joseeight

0

確保您的外部文件包含下面的內部

....... 

    <script> 

     function createRow(){ 
     console.log('created'); 
     } 

    </script> 

    <script src = "external.js"></script> 
</body> 
0

是有可能只有當你調用從HTML那裏是內部的JavaScript有外部js文件..

例子: 一html的

<html> 
<head> 
<script type="text/javascript"> 
    function displayAlert(){ 
     alert('displayAlert'); 
} 
    </script> 

    <script type="text/javascript" src="../../abc.js"></script> 
    </head> 
<body> 
//call the sample() javascript function which is in abc.js 
</body> 
</html> 

abc.js

function sample(){ 

displayAlert(); 

}