创建可重用的jQuery日期格式化程序

时间:2015-08-06 01:28:33

标签: jquery html ruby-on-rails

我有以下jQuery,我用它来格式化一个日期,以Rails接受的格式解析为DB(正斜杠不起作用)。

$('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实现转换为可重用的函数?

1 个答案:

答案 0 :(得分:0)

添加jQuery全局函数并不太难(确保在任何需要它的js之前执行):

l = [0]*port.shape[0]
count = 0
for i,j in enumerate(l):
    l[i] = count
    count += 1 
port = port.set_index(l)

使用它:

jQuery.fn.yourAwesomeFunction = function() {
  // your awesome function code goes here
};

希望这有帮助!