javascript - 如何在js函数的同一页面上创建多个实例
问题描述
考虑以下代码片段:
var from,to;
to = $(".range-to-dt").persianDatepicker({
inline: true,
minDate: new persianDate(cleanDate(serverDateTime)),
altField: '.range-to-dt-alt',
altFormat: 'YYYY/MM/DD',
initialValue: false,
onSelect: function (unix) {
to.touched = true;
if (from && from.options && from.options.maxDate != unix) {
var cachedValue = from.getState().selected.unixDate;
from.options = { maxDate: unix };
if (from.touched) {
from.setDate(cachedValue);
}
}
}
});
from = $(".range-from-dt").persianDatepicker({
inline: true,
observer: true,
minDate: new persianDate(cleanDate(serverDateTime)),
altField: '.range-from-dt-alt',
altFormat: 'YYYY/MM/DD',
initialValue: false,
onSelect: function (unix) {
from.touched = true;
if (to && to.options && to.options.minDate != unix) {
var cachedValue = to.getState().selected.unixDate;
to.options = { minDate: unix };
if (to.touched) {
to.setDate(cachedValue);
}
}
}
});
如何在同一页面上多次(以几种不同的形式)使用 js 函数以正确执行?
<form id="form1" ...>
<input asp-for="DateTimeRange.StartDate" ltr-input range-from-dt-alt">
<input asp-for="DateTimeRange.EndDate" ltr-input range-to-dt-alt">
</form>
<form id="form2" ...>
<input asp-for="DateTimeRange.StartDate" ltr-input range-from-dt-alt">
<input asp-for="DateTimeRange.EndDate" ltr-input range-to-dt-alt">
</form>
实际上如何在js函数的同一页面上创建多个实例?
解决方案
您必须遍历包含 2 个输入的每个表单。
例如,您可以在表单中添加一个类而不是 ID,例如
<form class="startEndForm">
// Your 2 inputs here
</form>
然后做这样的事情:
$('.startEndForm').each(function () {
$(this).find(".range-to-dt").persianDatepicker({
inline: true,
minDate: new persianDate(cleanDate(serverDateTime)),
altField: '.range-to-dt-alt',
altFormat: 'YYYY/MM/DD',
initialValue: false,
onSelect: function (unix) {
var from = $(this).parent().find('.range-from-dt');
var to = $(this);
to.touched = true;
if (from && from.options && from.options.maxDate != unix) {
var cachedValue = from.getState().selected.unixDate;
from.options = { maxDate: unix };
if (from.touched) {
from.setDate(cachedValue);
}
}
}
});
$(this).find(".range-from-dt").persianDatepicker({
inline: true,
observer: true,
minDate: new persianDate(cleanDate(serverDateTime)),
altField: '.range-from-dt-alt',
altFormat: 'YYYY/MM/DD',
initialValue: false,
onSelect: function (unix) {
var from = $(this);
var to = $(this).parent().find('.range-to-dt');
from.touched = true;
if (to && to.options && to.options.minDate != unix) {
var cachedValue = to.getState().selected.unixDate;
to.options = { minDate: unix };
if (to.touched) {
to.setDate(cachedValue);
}
}
}
});
});
推荐阅读
- angular - Safari 中的服务人员
- jquery - 如何让消息出现在无效反馈中?
- python - 为什么这组简单的连接会返回意外包装的结果?
- r - 如何从R中的对创建链
- excel - 从excel文件vba循环文件夹名称
- docker - 在 dockerfile 中从 github 安装 jenkins 插件
- c# - 我需要在 Identity Server 自定义登录页面的“用户名”字段中填充当前用户名
- mysql - 如何使用安装在 Windows 本地 xampp 上的 mysql 连接到我的数据库 URL(从 heroku 检索)
- go - 我可以列出所有标准的 Go 包吗?
- java - 具有不可见构造函数的公共类可以由另一个包中的类扩展吗?