jQuery优化-干燥

jQuery Optimization - Dry

本文关键字:干燥 优化 jQuery      更新时间:2024-02-15

我有一个简单的情况:

$("#check-in").dateDropper({
    years_multiple: "10",
    format: "d-m-Y",
    minYear: "2015",
    maxYear: "2016",
    lang: "pt",
    animation: "bounce",
    placeholder: "Dia da entrada."
});
$("#check-out").dateDropper({
    years_multiple: "10",
    format: "d-m-Y",
    minYear: "2015",
    maxYear: "2016",
    lang: "pt",
    animation: "bounce",
    placeholder: "Dia da saída."
});

唯一的区别是占位符:"…"。

如何优化此代码使其不重复(DRY)?

试试这个:

$("#check-in, #check-out").dateDropper({
    years_multiple: "10",
    format: "d-m-Y",
    minYear: "2015",
    maxYear: "2016",
    lang: "pt",
    animation: "bounce",
    placeholder:($(this).attr('id') == "check-in" ? "Dia da entrada." : "Dia da saída.")
});

试试这个:-

$("#check-in,#check-out").dateDropper({
    years_multiple: "10",
    format: "d-m-Y",
    minYear: "2015",
    maxYear: "2016",
    lang: "pt",
    animation: "bounce",
    placeholder: ($(this).attr('id') == "check-in" ? "Dia da entrada." : "Dia da saída.")
});
$("#check-in,#check-out").dateDropper({
    years_multiple: "10",
    format: "d-m-Y",
    minYear: "2015",
    maxYear: "2016",
    lang: "pt",
    animation: "bounce",
    placeholder: "Dia da "+($(this).attr('id') == "check-in" ? "entrada." : "saída.")
});
$("#check-in,#check-out").each(function(){
    var daylabel = this.id==="check-in" ? "entrada" : "saida";
    $(this).dateDropper({
        years_multiple: "10",
        format: "d-m-Y",
        minYear: "2015",
        maxYear: "2016",
        lang: "pt",
        animation: "bounce",
        placeholder: "Dia da "+daylabel+"."
    });
});