我在我的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);
})
});