我正在尝试通过 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']
});
}
});
}
通过调用 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>
我可以通过在浏览器中手动输入来导航到我创建的页面。我编写的 MySQL 查询工作正常,但当我尝试使用按钮导航时,出现引用错误:fetchpurchases 未定义
。
此外(可能不相关),当我尝试使用 Firebug 调试错误时,该函数不会显示在 DOM 窗口中。
最佳答案
我会做类似的事情
// Create a namespace for your code
var App = App || {};
(function() {
App.fetchpurchases = function() {
//Your code here
};
})();
如果您不想使用 JS 或 jQuery 将函数绑定(bind)到事件,您可以将 HTML 更改为:
<td><button onclick="App.fetchpurchases()" id="deliverSubmit" type="button">Confirm Delivery</button></td>
当然,无论你放在哪里,都需要将 javascript 添加到 application.js
或手动加载到页面中。
关于Javascript函数引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34095658/