我将 jquery datepicker 应用于具有类 txt-date
的输入元素:
$('.txt-date').datepicker({
showAnim: "blind",
changeMonth: true,
changeYear: true,
dateFormat: "dd.mm.yy",
numberOfMonths: 2
});
如您所见,我指定显示 2 个月。但这不是我想要的所有输入字段的行为。为了使其更加灵活,我想确定 numberOfMonths
的值基于自定义属性(如 data-shown-months
)值的属性。我尝试通过 $(this)
访问输入元素,像这样
<input type="text" class="txt-date" data-shown-months="2"/>
$('.txt-date').datepicker({
showAnim: "blind",
changeMonth: true,
changeYear: true,
dateFormat: "dd.mm.yy",
numberOfMonths: $(this).data('shown-months')
});
但这没有用。我试过$(this).attr('data-shown-months')
同样,以确保这不是 jquery data
的问题功能。看来$(this)
指日期选择器本身。至少它不引用源输入元素。您知道我如何访问源输入元素吗?
最佳答案
this
指的是调用 datepicker()
时的任何 this
(可能是 window
)。将 this
放置在对象参数中不会更改其上下文。
更改为:
$('.txt-date').datepicker({
numberOfMonths: $('.txt-date').data('shown-months') //"this" is probably window
});
如果您有多个具有“txt-date”类的元素,每个元素都有自己的“shown-months”值,您可以在 each() 中将它们全部初始化。 循环。在这种情况下,this
将指向每个元素:
$('.txt-date').each(function() {
$(this).datepicker({
numberOfMonths: $(this).data('shown-months') //"this" is the current element
});
});
关于jquery - 如何访问正在应用日期选择器的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37943202/