假设我有一些JavaScript代码,看起来像这样:
function CheckDateField()
{
if (!Modernizr.inputtypes.date) {
$(function () {
$(".datefield").datepicker();
});
}
}
这将检查浏览器的版本是否兼容 HTML 5,如果是,则使用日期字段;否则使用文本字段。
我的 .NET Core 视图有一个字段,如下所示:
<div class="form-group">
<label asp-for="DOB" class="control-label"></label>
@*@Html.TextBox("datepicker")*@
@Html.TextBox("datepicker", null, new { @readonly = "readonly" })
如何在 JavaScript 中使用该字段?我试过这个:
<label asp-for="DOB" class="control-label" onload="CheckDateField()"></label>
如果可能的话,最好将 JavaScript 直接放在 lavel 中。 我花了两个小时在谷歌上搜索这个,并尝试了一些方法,但没有奏效。
您只需在加载页面时检查HTML5 input date
功能并采取相应操作即可简化代码。 此外,您用于抓取元素的选择器将不起作用,因为input
没有设置类datefield
。
生成的标记如下所示:
<label for="dob">Date of birth</label>
<input type="date" name="dob" id="dob" class="datefield">
请注意缺少onload
事件处理程序,并且您首先将input type
设置为date
。
用于处理datepicker
的脚本位应类似于以下内容:
// When the document is ready.
$(function () {
// If input type date isn't supported.
if (!Modernizr.inputtypes.date) {
var el = $(".datefield");
// In a single call (chained) set the input type to text
// and attach the datepicker.
el.prop("type", "text").datepicker();
}
});
演示