简体   繁体   English

JavaScript函数参考错误

[英]Javascript function reference error

I am trying to call a Javascript function through a command button on my Rails app. 我正在尝试通过Rails应用程序上的命令按钮调用Javascript函数。

function fetchpurchases() {
  var startDate = $('#histStart').val();
  var endDate = $('#histEnd').val();
  $('#histMainFrame').empty();
  $.ajax({
    url: '/transHistory/confirm?start_date=' + startDate + '&end_date=' + endDate,
    type: 'get',
    beforeSend: function() {
      $('#mainContDiv').append('<img id=\'spinner\' src=\'/assets/spinner_green.gif\'>');
    },
    success: function(output) {
      $('#spinner').remove();
      $('#histMainFrame').html(output);
      $('#transPurTab').DataTable({
        destroy: true,
        lengthChange: false,
        pageLength: 50,
        paging: true,
        stripeClasses: ['oddStrip','evenStrip']
      });
    }
  });
}

A button is defined with the onclick event calling the Javascript function. 通过调用Javascript函数的onclick事件定义了一个按钮。

<div id="histToolbar">
  <div id="errorDiv"><p class="bigRedBright"></p></div>
  <table id="histTools">
    <tr>
      <th>Start Date</th>
      <th>End Date</th>
      <th></th>
    </tr>
    <tr>
        <td><input type="text" class="datepicker" id="histStart" placeholder="Start Date..."></td>
        <td><input type="text" class="datepicker" id="histEnd" placeholder="End Date..."></td>
        <td><button onclick="fetchHistory()" id="histSubmit">Submit</button></td>
        <td><button onclick="fetchpurchases()" id="deliverSubmit">Confirm Delivery</button></td>
    </tr>
  </table>
</div>

I can navigate to the page I created by typing it manually into the browser. 我可以通过在浏览器中手动键入页面来导航到我创建的页面。 The MySQL query I wrote works correctly, but when I try to navigate using the button, I get reference error: fetchpurchases is not defined . 我编写的MySQL查询工作正常,但是当我尝试使用按钮进行导航时,出现reference error: fetchpurchases is not defined

Additionally (may not be related), the function does not show up in the DOM window when I try to debug the error using Firebug. 另外(可能不相关),当我尝试使用Firebug调试错误时,该功能不会显示在DOM窗口中。

I would do something like so 我会做这样的事情

// Create a namespace for your code
var App = App || {};

(function() {
  App.fetchpurchases = function() {
    //Your code here
  };
})();

If you don't want to use JS or jQuery to bind the function to an event you can change your HTML to: 如果您不想使用JS或jQuery将函数绑定到事件,则可以将HTML更改为:

<td><button onclick="App.fetchpurchases()" id="deliverSubmit" type="button">Confirm Delivery</button></td>

Of course wherever you place that javascript needs to be added to application.js or loaded into the page manually. 当然,无论您放置在哪里,都需要将javascript添加到application.js或手动将其加载到页面中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM