创建一个可重用的jQuery日期格式化程序 [英] Creating a reusable jQuery date formatter

查看:115
本文介绍了创建一个可重用的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();

希望这会有所帮助!

这篇关于创建一个可重用的jQuery日期格式化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆