简体   繁体   English

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

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

I have a drop-down list with dates as options in it: 我有一个下拉列表,其中有日期作为选项:

<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>

I need to set the last date from the list (the most recent) as selected one. 我需要将列表中的最后一个日期(最新日期)设置为所选日期。 I've managed to do this by specifying the date manually. 我设法通过手动指定日期来做到这一点。 So how can I do it automatically in case if more dates will appear in the list as options in the future? 因此,如果将来有更多日期作为选项出现在列表中,我该如何自动执行呢?

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";
  });

You could do it based on the index of the datum instead. 您可以改为基于基准的索引来进行。 Let N = uniqueDates.length , then use: N = uniqueDates.length ,然后使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 jQuery、JavaScript 和 HTML 动态设置下拉列表的选定选项? - How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML? 如何使用取决于另一个下拉列表中所选选项的下拉列表显示表格简码 - how to display table shortcode with a drop-down list that depends on the selected option in another drop-down list 如何在当前时间的下拉菜单中设置自动选择的选项? - How to set auto selected option in drop-down with current time? 如何从下拉列表中隐藏选定的选项 - How can I Hide Selected option from Drop-down list 如何有条件地测试下拉列表中的所选选项/值 - How conditionally test the selected option/value from a drop-down list 使用jQuery从下拉列表中获取选定的文本 - Get selected text from a drop-down list using jQuery 从目录动态填充下拉列表,以便用户选择d3.js JSON数据 - Dynamically Fill Drop-down from Directory so User Selects d3.js JSON Data 如何使用D3.js设置下拉列表的位置? - How can I set the position of a drop down list with D3.js? 根据另一个下拉列表中的所选选项更改下拉列表中的项目 - Change items in a drop-down list depending on the selected option in another drop-down list 如何验证是否使用JavaScript从下拉列表中未选择任何内容 - how to validate if nothing is selected from drop-down using JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM