如何编写这个代码清洁,不重复?

时间:2017-12-15 19:17:57

标签: javascript jquery html css

  $("#yl").click(function(){updateYear("sub")});
  $("#yr").click(function(){updateYear("add")});
  $("#ml").click(function(){updateMonth("sub")});
  $("#mr").click(function(){updateMonth("add")});
  $("#dl").click(function(){updateDay("sub")});
  $("#dr").click(function(){updateDay("add")});

有没有办法编写这个代码更干净,更聪明而不重复?

2 个答案:

答案 0 :(得分:2)

如果稍微更改元素,可以执行以下操作:

<button id='yr' data-type='update' data-date-part='year' data-date-action='add'>

然后你创建一个像这样开始的更新函数:

function update() {
  const el = $(this);
  const datePart = el.attr('data-date-part');
  const dateAction = el.attr('data-date-action');

  // do your logic to update the date based on what part and action
}

然后你的点击处理程序只需要:

$('button[data-type="update"]').click(update);

我忘了提及,jquery的新版本也会让你只使用.data()函数而不是拼出完整的data-属性

答案 1 :(得分:0)

代码很好,因为它很清楚发生了什么。

如果你真的想以不同的方式做,那么你应该修改你的功能并查看HTML属性。这完全取决于你在这些功能中实际做了什么。

例如,如果您希望用户只需按添加/子按钮输入日期,那么基础知识可能如下所示:

&#13;
&#13;
$('.change-value').click(updateDatePart);

function updateDatePart() {
    // Read current date
    var dateParts = $.map($(this).closest(".dateinput").find(".part-value"), function (span) {
        return +$(span).text();
    });
    // Which part of the date needs incrementing/decrementing?
    var part = $(this).closest('.part').index();
    // Apply change to that part
    dateParts[part] += $(this).data("inc");
    // Create a date with this
    var date = new Date(dateParts[0], dateParts[1]-1, dateParts[2]);
    // Get the parts for the new date (which may have resolved some overflow)
    dateParts = [date.getFullYear(), date.getMonth()+1, date.getDate()];
    // Output the result
    $('.part-value').each(function (i, elem) {
        $(elem).text(dateParts[i]);
    });
}
&#13;
.change-value { font-size: 50% }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="dateinput">
    <span class="part">
        <button class="change-value" data-inc="-1">-</button>
        <span class="part-value">2017</span>
        <button class="change-value" data-inc="1">+</button>
    </span>-
    <span class="part">
        <button class="change-value" data-inc="-1">-</button>
        <span class="part-value">12</span>
        <button class="change-value" data-inc="1">+</button>
    </span>-
    <span class="part">
        <button class="change-value" data-inc="-1">-</button>
        <span class="part-value">24</span>
        <button class="change-value" data-inc="1">+</button>
    </span>
</span>
&#13;
&#13;
&#13;