jQuery优化 - 干

时间:2015-02-20 09:47:48

标签: javascript jquery dry datedropper

我有这种简单的情况:

$("#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)?

4 个答案:

答案 0 :(得分:1)

试试这个:

$("#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.")
});

答案 1 :(得分:1)

试试这个: -

$("#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.")
});

答案 2 :(得分:1)

$("#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.")
});

答案 3 :(得分:0)

$("#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+"."
    });
});