无法从外部脚本调用内联 javascript 函数

Can't call inline javascript function from external scripts

我在 body 标签的开头在内联脚本中声明了一个函数。 然后在外部脚本中。在表单上提交。它触发一个匿名函数 处理来自表单的数据并提交 $.ajax 方法。在文件末尾调用外部脚本

问题是我在我的表单标签中分配了一个函数名称作为 '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);
})
});

您的 searchResult 是您 ready 回调中的本地,无法从 ready 回调外部访问它。

您可以通过将其移出使其成为全球:

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

function searchResult(data) {
  alert()
}

...然后可以在该回调之外进行代码访问(例如在您的其他脚本中)。

但是全局变量是一件坏事™。 :-) 你可能会看看 Webpack, Browserify, or similar packaging/bundling systems that let you write discrete script files with dependencies, but without using globals, by using an import mechanism. (It's even possible to use the new import and export mechanism defined in ES2015+ [aka "ES6"] if you use a transpiler like Babel 和其中一个打包工具。)