我需要根据第一个框的选择来同步这两个下拉框。
在代码库从其他地方提取这些值时,我不能使用"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");有什么建议吗?
发布于 2019-05-13 02:29:11
首先,请注意,syncOne不是<select name="beta">的属性,而是与该选择器相关的每个选项都可用的属性,因此下一段代码不会产生您期望的结果:
document.getElementsByName("beta")[0].getAttribute("syncOne") = ...;现在,一种解决方案是使用querySelector()从beta选择器获取相关的option元素,然后设置该选项的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 + '"]');https://stackoverflow.com/questions/56104999
复制相似问题