JQuery 日期选择器 - 更改日期格式

JQuery datepicker - change date format

本文关键字:日期 格式 选择器 JQuery      更新时间:2023-09-26

我想在 JQuery 日期选择器中更改日期格式 (http://demos.jquerymobile.com/1.4.5/datepicker/)

使用函数日期格式 - http://api.jqueryui.com/datepicker/#option-dateFormat。

<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="http://cdn.rawgit.com/arschmitz/jquery-mobile-datepicker-wrapper/v0.1.1/jquery.mobile.datepicker.css">
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
        <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
        <script src="http://demos.jquerymobile.com/1.4.5/js/jquery.mobile-1.4.5.min.js"></script>
        <script src="http://cdn.rawgit.com/jquery/jquery-ui/1.10.4/ui/jquery.ui.datepicker.js"></script>
        <script id="mobile-datepicker" src="http://cdn.rawgit.com/arschmitz/jquery-mobile-datepicker-wrapper/v0.1.1/jquery.mobile.datepicker.js"></script>
        <script>
            $("#date").datepicker({
                dateFormat: "dd.mm.yy"
              });
        </script>
    </head>
    <body>
        <input data-role="date" type="text">
    </body>
</html>

为什么它不起作用?

看到这个小提琴

您缺少input id属性。由于您要将日期选择器初始化为 $("#date").datepicker() ,因此您必须指定一个id作为"输入"的日期。您在此处使用ID选择器。

请查看文档中的 jQuery 选择器。

.HTML

<input data-role="date" type="text" id="date">

.JS

$("#date").datepicker({
  dateFormat: "dd.mm.yy"
});

更新

由于您要在<head>中加载<script>,因此您必须使用$( document ).ready()。这是一个更新的小提琴。因此,更新后的JS将如下所示

$( document ).ready(function() {
    $("#date").datepicker({
       dateFormat: "dd.mm.yy"
    });
});

你需要用 document.ready 检查来包装你的块,否则,它将在 dom 存在之前执行并且什么都不做。

$( document ).ready(function() {
    $("#date").datepicker({
       dateFormat: "dd.mm.yy"
    });
});

您还需要在输入中添加一个 id:

<input data-role="date" type="text" id="date">