在jQuery UI datepicker中显示日期旁边的其他文本

时间:2022-08-26 22:56:48

I am using jQuery UI datepicker and I want to display additional text inside date cells next to the date. This is the desired behavior:

我正在使用jQuery UI datepicker,我想在日期旁边的日期单元格中显示其他文本。这是期望的行为:

在jQuery UI datepicker中显示日期旁边的其他文本

Unfortunately, manipulating date cells using .text() and .html() functions breaks the datepicker functionality. See following demo and try to use the datepicker. Notice that when you select a date (i) the custom text is gone (ii) changing months destroys the calendar and lands you on "undefined NaN" month:

不幸的是,使用.text()和.html()函数操作日期单元会破坏日期选择器功能。请参阅以下演示并尝试使用datepicker。请注意,当您选择日期时(i)自定义文本消失(ii)更改月份会破坏日历并让您登录“未定义的NaN”月份:

https://jsfiddle.net/salman/aLdx4L0y/

https://jsfiddle.net/salman/aLdx4L0y/

Is there a solution?

有解决方案吗?

4 个解决方案

#1


18  

Well, you can monkey-patch jQuery UI and risk breaking the code with newer versions or you can use documented callbacks to add custom data-* attributes to datepicker and display them using CSS pseudo elements:

好吧,你可以修补jQuery UI并冒险破坏新版本的代码,或者你可以使用文档化的回调将自定义data- *属性添加到datepicker并使用CSS伪元素显示它们:

$(function() {
  $("#datepicker").datepicker({
    beforeShow: addCustomInformation,
    //---^----------- if closed by default (when you're using <input>)
    beforeShowDay: function(date) {
      return [true, date.getDay() === 5 || date.getDay() === 6 ? "weekend" : "weekday"];
    },
    onChangeMonthYear: addCustomInformation,
    onSelect: addCustomInformation
  });
  addCustomInformation(); // if open by default (when you're using <div>)
});

function addCustomInformation() {
  setTimeout(function() {
    $(".ui-datepicker-calendar td").filter(function() {
      var date = $(this).text();
      return /\d/.test(date);
    }).find("a").attr('data-custom', 110); // Add custom data here
  }, 0)
}
.ui-datepicker .weekend .ui-state-default {
  background: #FEA;
}
.ui-datepicker-calendar td a[data-custom] {
  position: relative;
  padding-bottom: 10px;
}
.ui-datepicker-calendar td a[data-custom]::after {
  /*STYLE THE CUSTOME DATA HERE*/
  content: '$' attr(data-custom);
  display: block;
  font-size: small;
}
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<link href="//code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<input id="datepicker">

Here's an updated JSFiddle

这是一个更新的JSFiddle


Side note: I'm not sure which functionality is broke in your demo, but since this solution is using documented callbacks and CSS, I believe it's less likely to break anything in future than monkey patching

旁注:我不确定你的演示中有哪些功能被破坏,但由于这个解决方案使用了文档化的回调和CSS,我相信它不会在将来破坏任何东西而不是猴子修补

#2


11  

Since the jQuery UI datapicker is pretty monolithic it is difficult to enhance cleanly.

由于jQuery UI数据采集器非常单一,因此很难干净地增强。

I would go with monkey-patching one of its internal functions, namely _generateHTML.

我会选择猴子修补其内部函数之一,即_generateHTML。

$.datepicker._generateHTML = (function () {
    var realGenerateHtml = $.datepicker._generateHTML;
    return function (instance) {
        var html = realGenerateHtml.apply(this, arguments), $temp;
        
        if ( instance.input.is(".datepicker-price") ) {
            $temp = $("<table></table>").append(html);
            $temp.find(".ui-datepicker-calendar td a").each(function () {
                var yy = $(this).parent().data("year"),
                    mm = $(this).parent().data("month"),
                    dd = +$(this).text();

                $(this).append("<br><small class='price'>$100</small>");
            });
            html = $temp[0].innerHTML;
        }
        return html;
    };
})();

$(function() {
    $("#datepicker").datepicker();
});
.ui-datepicker .weekend .ui-state-default {
  background: #FEA;
}
.price {
    color: blue;
}
<link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>

<div id="datepicker" class="datepicker-price"></div>

#3


9  

There is a much simpler solution based on the accepted answer:

根据接受的答案,有一个更简单的解决方案:

The beforeShowDay function allows us to set the "title" attribute for each date. We can display the attribute using CSS pseudo elements.

beforeShowDay函数允许我们为每个日期设置“title”属性。我们可以使用CSS伪元素显示属性。

$(function() {
  var dayrates = [100, 150, 150, 150, 150, 250, 250];

  $("#datepicker").datepicker({
    beforeShowDay: function(date) {
      var selectable = true;
      var classname = "";
      var title = "\u20AC" + dayrates[date.getDay()];
      return [selectable, classname, title];
    }
  });
});
@import url("https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/blitzer/jquery-ui.min.css");

.ui-datepicker td span,
.ui-datepicker td a {
  padding-bottom: 1em;
}

.ui-datepicker td[title]::after {
  content: attr(title);
  display: block;
  position: relative;
  font-size: .8em;
  height: 1.25em;
  margin-top: -1.25em;
  text-align: right;
  padding-right: .25em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<div id="datepicker"></div>

#4


7  

Add this code into your JS...

将此代码添加到您的JS中...

$('#DatePicker').datepicker({
changeMonth: true,
changeYear: true,
minDate: 0,
onSelect: function (date, dp) {
    updateDatePickerCells();
},
onChangeMonthYear: function(month, year, dp) {
    updateDatePickerCells();
},
beforeShow: function(elem, dp) { 
    updateDatePickerCells();
}});
updateDatePickerCells();
function updateDatePickerCells(dp) {

setTimeout(function () {

    var cellContents = {1: '20', 15: '60', 28: '$99.99'};


    $('.ui-datepicker td > *').each(function (idx, elem) {
        var value = '$125';//cellContents[idx + 1] || 0;


        var className = 'datepicker-content-' + CryptoJS.MD5(value).toString();

        if(value == 0)
            addCSSRule('.ui-datepicker td a.' + className + ':after {content: "\\a0";}'); //&nbsp;
        else
            addCSSRule('.ui-datepicker td a.' + className + ':after {content: "' + value + '";}');

        $(this).addClass(className);
    });
}, 0);
}
var dynamicCSSRules = [];
function addCSSRule(rule) {
if ($.inArray(rule, dynamicCSSRules) == -1) {
    $('head').append('<style>' + rule + '</style>');
    dynamicCSSRules.push(rule);
}
}

Demo link... http://jsfiddle.net/pratikgavas/e3uu9/131/

演示链接... http://jsfiddle.net/pratikgavas/e3uu9/131/

#1


18  

Well, you can monkey-patch jQuery UI and risk breaking the code with newer versions or you can use documented callbacks to add custom data-* attributes to datepicker and display them using CSS pseudo elements:

好吧,你可以修补jQuery UI并冒险破坏新版本的代码,或者你可以使用文档化的回调将自定义data- *属性添加到datepicker并使用CSS伪元素显示它们:

$(function() {
  $("#datepicker").datepicker({
    beforeShow: addCustomInformation,
    //---^----------- if closed by default (when you're using <input>)
    beforeShowDay: function(date) {
      return [true, date.getDay() === 5 || date.getDay() === 6 ? "weekend" : "weekday"];
    },
    onChangeMonthYear: addCustomInformation,
    onSelect: addCustomInformation
  });
  addCustomInformation(); // if open by default (when you're using <div>)
});

function addCustomInformation() {
  setTimeout(function() {
    $(".ui-datepicker-calendar td").filter(function() {
      var date = $(this).text();
      return /\d/.test(date);
    }).find("a").attr('data-custom', 110); // Add custom data here
  }, 0)
}
.ui-datepicker .weekend .ui-state-default {
  background: #FEA;
}
.ui-datepicker-calendar td a[data-custom] {
  position: relative;
  padding-bottom: 10px;
}
.ui-datepicker-calendar td a[data-custom]::after {
  /*STYLE THE CUSTOME DATA HERE*/
  content: '$' attr(data-custom);
  display: block;
  font-size: small;
}
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<link href="//code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<input id="datepicker">

Here's an updated JSFiddle

这是一个更新的JSFiddle


Side note: I'm not sure which functionality is broke in your demo, but since this solution is using documented callbacks and CSS, I believe it's less likely to break anything in future than monkey patching

旁注:我不确定你的演示中有哪些功能被破坏,但由于这个解决方案使用了文档化的回调和CSS,我相信它不会在将来破坏任何东西而不是猴子修补

#2


11  

Since the jQuery UI datapicker is pretty monolithic it is difficult to enhance cleanly.

由于jQuery UI数据采集器非常单一,因此很难干净地增强。

I would go with monkey-patching one of its internal functions, namely _generateHTML.

我会选择猴子修补其内部函数之一,即_generateHTML。

$.datepicker._generateHTML = (function () {
    var realGenerateHtml = $.datepicker._generateHTML;
    return function (instance) {
        var html = realGenerateHtml.apply(this, arguments), $temp;
        
        if ( instance.input.is(".datepicker-price") ) {
            $temp = $("<table></table>").append(html);
            $temp.find(".ui-datepicker-calendar td a").each(function () {
                var yy = $(this).parent().data("year"),
                    mm = $(this).parent().data("month"),
                    dd = +$(this).text();

                $(this).append("<br><small class='price'>$100</small>");
            });
            html = $temp[0].innerHTML;
        }
        return html;
    };
})();

$(function() {
    $("#datepicker").datepicker();
});
.ui-datepicker .weekend .ui-state-default {
  background: #FEA;
}
.price {
    color: blue;
}
<link href="https://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>

<div id="datepicker" class="datepicker-price"></div>

#3


9  

There is a much simpler solution based on the accepted answer:

根据接受的答案,有一个更简单的解决方案:

The beforeShowDay function allows us to set the "title" attribute for each date. We can display the attribute using CSS pseudo elements.

beforeShowDay函数允许我们为每个日期设置“title”属性。我们可以使用CSS伪元素显示属性。

$(function() {
  var dayrates = [100, 150, 150, 150, 150, 250, 250];

  $("#datepicker").datepicker({
    beforeShowDay: function(date) {
      var selectable = true;
      var classname = "";
      var title = "\u20AC" + dayrates[date.getDay()];
      return [selectable, classname, title];
    }
  });
});
@import url("https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/blitzer/jquery-ui.min.css");

.ui-datepicker td span,
.ui-datepicker td a {
  padding-bottom: 1em;
}

.ui-datepicker td[title]::after {
  content: attr(title);
  display: block;
  position: relative;
  font-size: .8em;
  height: 1.25em;
  margin-top: -1.25em;
  text-align: right;
  padding-right: .25em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

<div id="datepicker"></div>

#4


7  

Add this code into your JS...

将此代码添加到您的JS中...

$('#DatePicker').datepicker({
changeMonth: true,
changeYear: true,
minDate: 0,
onSelect: function (date, dp) {
    updateDatePickerCells();
},
onChangeMonthYear: function(month, year, dp) {
    updateDatePickerCells();
},
beforeShow: function(elem, dp) { 
    updateDatePickerCells();
}});
updateDatePickerCells();
function updateDatePickerCells(dp) {

setTimeout(function () {

    var cellContents = {1: '20', 15: '60', 28: '$99.99'};


    $('.ui-datepicker td > *').each(function (idx, elem) {
        var value = '$125';//cellContents[idx + 1] || 0;


        var className = 'datepicker-content-' + CryptoJS.MD5(value).toString();

        if(value == 0)
            addCSSRule('.ui-datepicker td a.' + className + ':after {content: "\\a0";}'); //&nbsp;
        else
            addCSSRule('.ui-datepicker td a.' + className + ':after {content: "' + value + '";}');

        $(this).addClass(className);
    });
}, 0);
}
var dynamicCSSRules = [];
function addCSSRule(rule) {
if ($.inArray(rule, dynamicCSSRules) == -1) {
    $('head').append('<style>' + rule + '</style>');
    dynamicCSSRules.push(rule);
}
}

Demo link... http://jsfiddle.net/pratikgavas/e3uu9/131/

演示链接... http://jsfiddle.net/pratikgavas/e3uu9/131/