这个JavaScript如何工作?

Joh*_*Doe 1 javascript jquery razor

当我使用时,这个功能如何适用于所有文本框

$('#date, #date2').blur(function () {

但不是我用的时候

$('#date').blur(function () {

MVC查看器:

@Html.TextBoxFor(x => x.ArrivalDateStart, new { id = "date" })
@Html.TextBoxFor(x => x.ArrivalDateEnd, new { id = "date" })
@Html.TextBoxFor(x => x.OtherDateEnd, new { id = "date" })
@Html.TextBoxFor(x => x.OtherDateEnd, new { id = "date" })
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

$(function () {
    $('#date, #date2').blur(function () {
        var date = $(this).val();
        var result = "";
        if (date.length === 8) {
            result = result += date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8);
            $(this).val(result);
            $(this).blur()
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

Asa*_*din 11

您的元素应具有唯一ID.将其转换为类属性而不是ID属性:

@Html.TextBoxFor(x => x.ArrivalDateStart, new { @class = "date" })
Run Code Online (Sandbox Code Playgroud)

并选择它像这样:

$('.date').blur(function () {
Run Code Online (Sandbox Code Playgroud)