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

时间:2018-12-20 03:44:50

标签: javascript html forms d3.js

我有一个带有<select>元素的交互式图形(一个下拉菜单)。效果很好-除了在Internet Explorer中。

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

  • 收听用户更改<select>元素;
  • 将所选值存储为变量;
  • 根据选择的内容为下拉菜单创建一个新的数据列表;
  • 使用此数据列表在<option>元素中重新填充<select>元素;和
  • <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>

1 个答案:

答案 0 :(得分:1)

如何将选项的属性设置为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>