[英]How to call a internal script function from external js file method?
我正在借助外部js文件使用MVC4應用程序。 在視圖(.cshtml)文件中,我具有一個函數,該函數基於單擊按鈕執行在網格中創建行的操作。 我已經在外部.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>
這很可能是由於范圍問題。 內部腳本和外部腳本必須在不同的范圍內。 解決此問題的最簡單,最棘手的方法是將內部方法添加到Window,並在外部這樣訪問它。
//Internal script
function myInternalMethod () {
//some code..
}
window.myInternalMethod = myInternalMethod;
由於window是全局的,並且名稱相同,因此在外部腳本中引用window.myInternalMethod或myInternalMethod時,可以使用它。
確保您的外部文件包含在內部文件下方
.......
<script>
function createRow(){
console.log('created');
}
</script>
<script src = "external.js"></script>
</body>
是的,只有當您從內部JavaScript所在的html調用該外部js文件時,才有可能。
范例:a.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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.