首页 > 解决方案 > 在 Internet Explorer 中,如何以编程方式更改“选择”元素的(显示)值?

问题描述

我有一个带有<select>元素的交互式图形(下拉菜单)。它工作正常——除了在 Internet Explorer 中。

本质上,我不能以编程方式更改<select>IE 中元素的选定(并因此显示)值。我需要以编程方式执行此操作,因为每次用户进行更改时都会动态填充<option>元素中的元素。<select>我的程序(不是下面的那个):

下面是问题的一个版本(我用 编码d3.js)。下面的代码<select>每秒更改元素的值。它在大多数浏览器中都可以正常工作 - 但请尝试在 IE 中查看:

<select></select>
<h1></h1>

<script src="https://d3js.org/d3.v4.min.js"></script>

<script>
  selector = d3.select("select"),
  answer = d3.select("h1"),
  fruit = ["apricots", "apples", "bananas", "grapefruit", "lemons", "oranges", "plums", "tangerines"];

  // fill the drop-down menu with fruit
  selector.selectAll("option")
      .data(fruit)
    .enter().append("option")
      .text(function(d) { return d; });

  // display the selected value under the menu
  answer.text(selector.property("value"));

  // change the selection every second
  changeValue = d3.interval(function() {
    selector.property("value", fruit[Math.random() * fruit.length | 0]);
    answer.text(selector.property("value"));
  }, 1000);
</script>

标签: javascripthtmlformsd3.js

解决方案


将选项的属性设置为 selected 怎么样(而不是将 select 的值设置为选项)。它在 IE 中对我有用:

  selector = d3.select("select"),
  answer = d3.select("h1"),
  fruit = ["apricots", "apples", "bananas", "grapefruit", "lemons", "oranges", "plums", "tangerines"];

  // fill the drop-down menu with fruit
  selector.selectAll("option")
      .data(fruit)
    .enter().append("option")
      .text(function(d) { return d; });

  // display the selected value under the menu
  answer.text(selector.property("value"));

  // change the selection every second
  changeValue = d3.interval(function() {
    var random = Math.floor(Math.random() * fruit.length);
    selector.selectAll("option").filter(function(d,i) { return i == random }).property("selected",true);
   // selector.property("value", fruit[Math.random() * fruit.length | 0]);
    answer.text(selector.property("value"));
  }, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<select></select>
<h1></h1>


推荐阅读