2017-02-23 84 views
0

我在我的body標籤的開頭聲明瞭內聯腳本中的函數。 然後在外部腳本中。在表單上提交。它會觸發一個匿名函數 ,它處理表單中的數據並提交$ .ajax方法。在文件末尾調用外部腳本無法從外部腳本調用內嵌JavaScript函數

問題是我在表單標記中爲函數名稱指定了'data-success =「functionName」'。它會觸發外部腳本中的功能。 但外部腳本不能識別html文件中調用的內聯函數。

這裏是一個例子。 https://jsfiddle.net/vsbmn8w1/?utm_source=website&utm_medium=embed&utm_campaign=vsbmn8w1

HTML

<script> 
    $(document).ready(function() { 

    // The Inline function that dont get called externally 
    function searchResult(data) { 
     alert() 
    } 
}); 
</script> 

<!-- Trigger On Submit --> 
<form method="post" class="async-form" data-success="searchResult"> 
    <button type="submit">submit</button> 
</form> 

外部腳本

$(document).ready(function() { 
    $(document).on("submit", "form.async-form", function(event) { 
    // Declare form in a variable 
    var $this = $(this); 

    // Prevent Page reloading 
    event.preventDefault(); 

    // Collect Form parameters 
    var action = $this.prop('action'); 
    var method = $this.prop('method'); 
    var form = $this.serialize(); 

    // Default request object 
    var request = { 
    url: action, 
    type: method, 
    data: form 
    }; 

    // Adding parameter to the object if data exist 
    if (typeof $this.data('success') != 'undefined') { 
    request['success'] = $this.data('success'); 
    } 
    if (typeof $this.data('error') != 'undefined') { 
    request['error'] = $this.data('error'); 
    } 
    if (typeof $this.data('beforeSend') != 'undefined') { 
    request['beforeSend'] = $this.data('beforeSend'); 
    } 
    if (typeof $this.data('complete') != 'undefined') { 
    request['complete'] = $this.data('complete'); 
    } 

    // Finally make the ajax request 
    $.ajax(request); 
}) 
}); 

回答

3

searchResult是你ready回調中的一個局部,它不是從ready回調外部訪問。

你可以把它的全球移動出來:

$(document).ready(function() { 
    // ...anything that needs to wait goes here... 
}); 

function searchResult(data) { 
    alert() 
} 

...然後它會進入到回調以外的程序(如在其它腳本)。

但globals是一個壞事™。 :-)您可以看看Webpack,Browserify或類似的打包/捆綁系統,這些系統可讓您使用導入機制編寫具有依賴關係的離散腳本文件,但不使用全局變量。 (它甚至可以用在ES2015 + [又名「ES6」]定義的,如果你使用像Babel和那些捆紮機之一transpiler新importexport機制。)

相關問題