2017-02-23 88 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机制。)