2015-12-04 115 views
1

我想通过我的Rails应用程序上的命令按钮调用Javascript函数。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查询工作正常,但是当我尝试使用按钮导航时,我得到reference error: fetchpurchases is not defined

此外(可能不相关),当我尝试使用Firebug调试错误时,函数不会显示在DOM窗口中。

+0

'fetchpurchases'绑定到窗口?你可以尝试将它附加到窗口中,或者更好地将一个'App'对象附加到窗口并将你的函数放在那里以命名空间。 – CWitty

回答

0

我会做一些像这样

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

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

如果你不想用JS或jQuery来的功能结合到一个事件您可以将HTML改为:

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

当然,无论你放置那个JavaScript需要被添加到application.js或手动加载到页面。