如何将下拉列表中的最后一个选项设置为使用D3.js选择

How to set the last option from a drop-down list as selected using D3.js

本文关键字:D3 选择 js 设置 选项 下拉列表 最后一个      更新时间:2023-09-26

我有一个下拉列表,其中日期作为选项:

<select id="dateSelector">
  <option value="2016-01-01">Январь 2016</option>
  <option value="2016-02-01">Февраль 2016</option>
  <option value="2016-03-01">Март 2016</option>
</select>

我需要将列表中的最后一个日期(最近的)设置为所选日期。我已经设法通过手动指定日期来做到这一点。那么,如果将来有更多的日期会作为选项出现在列表中,我该如何自动执行呢?

d3.select("select#dateSelector")
  .selectAll("option")
  .data(uniqueDates)
  .enter()
  .append("option")
  .text(function(d) {
    return formatRU(new Date(d));
  })
  .attr("value", function(d) {
    return d;
  })
  .property("selected", function(d) {
    return d === "2016-03-01";
  });

您可以根据数据的索引来执行。设N = uniqueDates.length,则使用:

.property("selected", function(d, i) { return i == N-1; })