2017-02-23 29 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() 
} 

を...そして、(あなたの他のスクリプトのように)、そのコールバック外部のコードにアクセス可能になります。

あなたはそれを移動することで、それがグローバル作ることができます。

しかし、グローバルはBad Thing™です。 :-) WebpackBrowserify、または同様のパッケージング/バンドルシステムを見て、インポートメカニズムを使用して、グローバルを使用せずに、依存関係のある個別のスクリプトファイルを書くことができます。 (Babelのようなトランスファーを使用する場合は、新しいimportexportメカニズムをES2015 + [別名「ES6」]で定義することもできます)

関連する問題