Отображать дополнительный текст вместе с датами в jQuery UI datepicker
Я использую jQuery UI datepicker, и я хочу отображать дополнительный текст внутри ячеек даты рядом с датой. Это желаемое поведение:
![jQuery UI datepicker с пользовательским текстом внутри ячеек]()
К сожалению, манипулирование ячейками дат с использованием функций .text()
и .html()
ломает функциональность datepicker. См. Следующую демонстрацию и попробуйте использовать datepicker. Обратите внимание, что когда вы выбираете дату (i), пользовательский текст уходит (ii) изменения месяцев уничтожают календарь и помещают вас в месяц "undefined NaN":
https://jsfiddle.net/salman/aLdx4L0y/
Есть ли решение?
Ответы
Ответ 1
Ну, вы можете использовать интерфейс jQuery для обезьян-патчей и риск взлома кода с более новыми версиями, или вы можете использовать документированные обратные вызовы для добавления пользовательских атрибутов 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">
Ответ 2
Поскольку jQuery UI datapicker довольно монолитен, его сложно улучшить чисто.
Я бы пошел с обезьяной, исправляя одну из своих внутренних функций, а именно _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
Добавьте этот код в свой 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";}'); //
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);
}
}
Демо-ссылка...
http://jsfiddle.net/pratikgavas/e3uu9/131/
Ответ 4
Существует гораздо более простое решение, основанное на принятом ответе:
Функция 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("//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="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div id="datepicker"></div>