javascript - getAttribute 未设置
问题描述
我需要根据第一个框的选择来同步这两个下拉框。
我不能"value"
为此使用标签,因为代码库从其他地方提取这些值。
以下代码不起作用:
html
<select name="alpha">
<option id="1" data-sync="1">One</option>
<option id="2" data-sync="2" selected>Two</option>
<option id="3" data-sync="3">Three</option>
<option id="4" data-sync="1">Four One</option>
<option id="5" data-sync="2">Five Two</option>
</select>
<select name="beta">
<option value="1" id="1" name="1" syncOne="1">2</option>
<option value="2" name="2" id="2" syncOne="2">4</option>
<option value="3" name="3" id="3" syncOne="3">6</option>
</select>
JavaScript
window.onload = function()
{
document.getElementsByName("alpha")[0].onchange = function()
{
document.getElementsByName("beta")[0].getAttribute("syncOne") = this.options[this.selectedIndex].getAttribute("data-sync");
}
// Trigger when loading.
document.getElementsByName("alpha")[0].onchange();
}
但是,下一个代码更改有效,但超出了项目规范(我不能使用value
属性)。
document.getElementsByName("beta")[0].value = this.options[this.selectedIndex].getAttribute("data-sync");
有什么建议么?
解决方案
首先,请注意这syncOne
不是 的属性<select name="beta">
,而是与该选择器相关的每个选项上可用的属性,因此下一个代码不会产生您所期望的结果:
document.getElementsByName("beta")[0].getAttribute("syncOne") = ...;
现在,一种解决方案是使用querySelector()从选择器中获取相关option
元素beta
,然后设置该selected
选项的属性:
例子:
window.onload = function()
{
document.getElementsByName("alpha")[0].onchange = function()
{
let sel = this.options[this.selectedIndex].getAttribute("data-sync");
let betaOpt = document.querySelector(`select[name="beta"] option[syncOne="${sel}"]`);
betaOpt.selected = true;
}
// Trigger when loading.
document.getElementsByName("alpha")[0].onchange();
}
<select name="alpha">
<option id="1" data-sync="1">One</option>
<option id="2" data-sync="2" selected>Two</option>
<option id="3" data-sync="3">Three</option>
<option id="4" data-sync="1">Four One</option>
<option id="5" data-sync="2">Five Two</option>
</select>
<select name="beta">
<option value="1" id="1" name="1" syncOne="1">2</option>
<option value="2" name="2" id="2" syncOne="2">4</option>
<option value="3" name="3" id="3" syncOne="3">6</option>
</select>
请注意,我使用模板文字(ES6
功能)来生成querySelector()
. 如果您不能使用它,您可以使用字符串连接,如下所示:
let betaOpt = document.querySelector('select[name="beta"] option[syncOne="' + sel + '"]');
推荐阅读
- java - 有没有一种简单的方法可以让 android VideoView 播放 .mp4 文件?
- spring-data-redis - spring-data-redis 2.x 将 RedisTemplate 与 RedisCacheManager 和 redisson 用于 connectionfactory
- google-cloud-platform - 已知转录本的 Google 语音识别时间戳
- python - 如何在内部转储带有导入的函数
- javascript - Javascript ES6:为展开函数实现生成器
- java - 邮递员“状态”:415,“错误”:“不支持的媒体类型”,
- python - 自动化上面的功能,所以我不必每次都写一个额外的术语
- python - 将 manim TextMobjects 组合成一个动画对象?
- matlab - Matlab:设置 ButtonDownFcn 会在悬停时禁用默认数据提示功能
- css - 带有关闭按钮的纯基于 CSS 的下拉菜单