创建一个可重用的jQuery日期格式化程序
问题描述:
我有以下jQuery,用于将要解析的日期格式化为Rails接受的格式(正斜杠不起作用).
I have the following jQuery which I use to format a date to be parsed to the DB (forward slashes don't work) in a format Rails will accept.
$('input#expClosingDateDisplay').change(function() {
var expClosingDateDisplay = $(this).val().split('/');
var formattedexpClosingDate = expClosingDateDisplay[2] + '-' + expClosingDateDisplay[1] + '-' + expClosingDateDisplay[0]
$('input#expClosingDate').val('');
if (expClosingDateDisplay != '') {
$('input#expClosingDate').val(formattedexpClosingDate);
}
});
html
<input id="expClosingDateDisplay" class="fdatepicker" placeholder="dd/mm/yyyy" type="text" value="<%= @real_property_sale_project.expected_closing_date.try(:strftime, "%d/%m/%Y") %>">
<%= f.hidden_field :expected_closing_date, id: "expClosingDate" %>
这可以正常工作,但是我想在整个应用程序中使用此功能,因为我有许多日期字段.我该如何将当前的jQuery实现变成可重用的函数?
This works as it should but I would like to use this function throughout my application as I have a number of date fields. How would I go about turning my current jQuery implementation into a reusable function?
答
添加jQuery全局函数并不难(请确保在执行所有需要它的js之前执行):
Adding a jQuery global function isn't too tough (make sure this executes before any js that'll need it):
jQuery.fn.yourAwesomeFunction = function() {
// your awesome function code goes here
};
并使用它:
$('.some-selector').yourAwesomeFunction();
希望这会有所帮助!