-2

如何在 jquery 中最小化以下绑定:

    var profileIdDefault = "Profile ID";
    var organisationIdDefault = "Competitor ID";
    var FromDateDefault = "From Date";
    var ToDateDefault = "To Date";


    $("#startDate").focus(function () {
        if ($(this).val() === FromDateDefault) {
            $(this).attr("value", "");
        }
    });
    $("#startDate").blur(function () {
        if ($(this).val() === '') {
            $(this).val(FromDateDefault);
        }
    });

    $("#endDate").focus(function () {
        if ($(this).val() === ToDateDefault) {
            $(this).attr("value", "");
        }
    });
    $("#endDate").blur(function () {
        if ($(this).val() === '') {
            $(this).val(ToDateDefault);
        }
    });

    $("#profileID").focus(function () {
        if ($(this).val() === profileIdDefault) {
            $(this).attr("value", "");
        }
    });
    $("#profileID").blur(function () {
        if ($(this).val() === '') {
            $(this).val(profileIdDefault);
        }
    });

    $("#organisationID").focus(function () {
        if ($(this).val() === organisationIdDefault) {
            $(this).attr("value", "");
        }
    });
    $("#organisationID").blur(function () {
        if ($(this).val() === '') {
            $(this).val(organisationIdDefault);
        }
    });
4

4 回答 4

3

保持干燥。例子:

function setup(id, toCompare) {
    $(id).focus(function () {
        if ($(this).val() === toCompare) {
            $(this).attr("value", "");
        }
    }).blur(function () {
        if ($(this).val() === '') {
            $(this).val(toCompare);
        }
    });
}
setup("#startDate", FromDateDefault);
setup("#endDate", ToDateDefault);
setup("#profileID", profileIdDefault);
setup("#organisationID", organisationIdDefault);
于 2013-04-25T08:42:41.720 回答
2

您也可以使用占位符简单地做到这一点

<input id="startdate" placeholder="From Date" /><br />
<input id="endDate" placeholder="To Date" /><br />

小提琴

于 2013-04-25T08:47:24.683 回答
0

你可以这样做: -

function toggleValue(valToCompare) {
     if ($(this).val() === valToCompare) {
         $(this).attr("value", "");
     } else if ($(this).val() === '') {
         $(this).val(valToCompare);
     }
}

$("#startDate").focus(function() {
    this.toggleValue(FromDateDefault);
}).blur(function() {
    this.toggleValue(FromDateDefault);
});

您可以对其余元素执行相同操作。

于 2013-04-25T08:39:20.220 回答
0

您可以使用 data 属性将一些数据存储在元素中。然后您可以测试与元素关联的值。例如...

<input id="startdate" class="focus-value" data-empty="From Date" />
<input id="enddate" class="focus-value" data-empty="To Date" />

在jquery...

$(".focus-value").focus(function() { 
    if $(this).val() === $(this).data('empty') { 
         $(this).attr("value", "");
    }
});

允许您组合所有焦点和模糊处理程序。

于 2013-04-25T08:43:21.107 回答