javascript - 在 Internet Explorer 中,如何以编程方式更改“选择”元素的(显示)值?
问题描述
我有一个带有<select>
元素的交互式图形(下拉菜单)。它工作正常——除了在 Internet Explorer 中。
本质上,我不能以编程方式更改<select>
IE 中元素的选定(并因此显示)值。我需要以编程方式执行此操作,因为每次用户进行更改时都会动态填充<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>
解决方案
将选项的属性设置为 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>
推荐阅读
- javascript - React DOM 在状态更改后不会重新渲染/更新
- javascript - 如何在 Nuxt.js 生成时动态使用 v-if?
- json - 将 JSONtoken 转换为数据源的更好方法
- go - 如何理解 bazel coverage coverage.dat 文件?
- bash - cat file_name | 之间的区别 排序,排序 < 文件名,在 bash 中排序文件名
- python - 如何在熊猫中处理带逗号的列名
- java - Spring Boot Logback 配置文件记录器问题
- python - 在当前类的循环中调用另一个类函数
- python - 将 statsmodels logit 返回的参数约束为正值
- javascript - 在没有任何插件的情况下在 javascript 或 jquery 中延迟加载视频